Learning jqPlot
上QQ阅读APP看书,第一时间看更新

Adding a fill between two lines

We talk through Calvin's comments. Adding in expenses won't be too much of an issue. We could simply add the expense line to one of our existing reports but that will likely not be what they want. Visually, the gap on our chart between profit and revenue should be the total amount of expenses. You mention that we could fill in the gap between the two lines. We decide to give this a try:

  1. We leave the plugins and the data arrays alone. We pass an empty array into our data array as a placeholder for our expenses. Next, we update our title. After this, we add a new series object and label it Expenses:
    ...
        var rev_profit = $.jqplot ('revPrfChart', [revenue, profit, []],
        {
          title:'Monthly Revenue & Profit with Highlighted Expenses',
          series:[ { label: 'Revenue' }, { label: 'Profit' }, { label: 'Expenses' } ],
          legend: { show: true, placement: 'outsideGrid' },
  2. To fill in the gap between the two lines, we use the fillBetween option. The only two required options are series1 and series2. These require the positions of the two data series in the data array. So in our chart, series1 would be 0 and series2 would be 1.

    The other three optional settings are: baseSeries, color, and fill. The baseSeries option tells jqPlot to place the fill on a layer beneath the given series. It will default to 0. If you pick a series above zero, then the fill will hide any series below the fill layer:

     
    fillBetween: {
            series1: 0,
            series2: 1,
    
  3. We want to assign a different value to color because it will default to the color of the first data series option. The color option will accept either a hexadecimal value or the rgba option, which allows us to change the opacity of the fill. Even though the fill option defaults to true, we explicitly set it. This option also gives us the ability to turn off the fill after the chart is rendered:
     
    color: "rgba(232, 44, 12, 0.5)",
            fill: true
          },
    
  4. The settings for the rest of the chart remain unchanged:
          axes:{
            xaxis:{
              renderer:$.jqplot.DateAxisRenderer,
              label: 'Months'
            },
            yaxis:{
              label: 'Totals Dollars',
              tickOptions: {
                formatString: "$%'d"
              }
            }
          }
        });
    });
    </script>
    <div id="revPrfChart" style="width:600px;"></div>

We switch back to our web browser and load the new page. We see the result of our efforts in the following screenshot. This chart layout works but we think Calvin and the others will want something else. We decide we need to make an area chart: