Search code examples
c#sql-serverdata-bindingmschartbubble-chart

Plot bubble chart for data-bound values, including bubble size


i tried the Points.AddXY method as well but it gave the chart as shown in image.

I have a table (table name is ex1, it has 3 columns: x,y and size) in sql server.

I have connected to this table from C# and want to display the contents as a bubble chart in my application. I am able to plot values of x and y axis but cannot get the bubble sizes for y values right.

I have shared the code below. This code plots x values on the x axis correctly, but uses the value of 'size' column to plot y values.

    private void button1_Click(object sender, EventArgs e)
    {
        chart4.Series["Series2"].ChartType = SeriesChartType.Bubble;
        chart4.Series["Series2"].MarkerStyle = MarkerStyle.Circle;
        SqlConnection con0 = new SqlConnection(
         "Data Source=4L861280\\sqlexpress;Initial Catalog=vis1;Integrated Security=True;");
        SqlDataAdapter ad0 = new SqlDataAdapter("select * from ex1", con0);
        DataTable dt0 = new DataTable();
        ad0.Fill(dt0);
        chart4.DataSource = dt0;
        chart4.Series["Series2"].XValueMember = "x";
        chart4.Series["Series2"].YValueMembers = "y";
        chart4.Series["Series2"].YValueMembers = "size";
       }

Solution

  • You need to get the syntax for binding with multiple y-values right.

    Here is an example:

    yourSeries.Points.DataBind(yourDataSource, "x", "y,size", "");
    

    The trick is to append the second y-value for the size with a comma to the first one. The third string is for extra attributes you may want to bind, like AxisLabel, Tooltip, Label, LegendText, LegendTooltip and CustomPropertyName (the name of a custom property)...

    They are given as named key-value pairs like this: "Tooltip=X,otherproperty=otherfield"

    Here is a longer discussion and here is an encouraging result:

    enter image description here

    The same rules can be applied to the syntax you used:

    chart4.DataSource = dt0;
    chart4.Series["Series2"].XValueMember  = "x";
    chart4.Series["Series2"].YValueMembers = "y,size";
    

    Note that this way of binding doesn't allow setting the extra attibutes. See here for a good overview of the many ways of binding data to a Chart.