DEV Community

Cover image for Visualize the Average U.S. Gasoline Price Over Time Using React Line Chart
Jollen Moyani for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

Visualize the Average U.S. Gasoline Price Over Time Using React Line Chart

TL;DR: Let’s see how to visualize U.S. gasoline price fluctuations in 2024 using the Syncfusion React Line Chart. The blog covers collecting monthly price data, structuring it for the chart, and binding it to the chart component. You’ll also learn to enhance the chart with titles, tooltips, annotations, and custom visuals for better insights. Discover seasonal trends and economic impacts with an interactive chart.

Welcome to the first blog of the series, Weekly Web Visualization Insights!

Today, we’ll demonstrate how to create a line chart to visualize the fluctuations in gasoline prices across the U.S. in 2024 using the Syncfusion React Charts control.

In 2024, gasoline prices experienced notable variations, driven by global supply and demand dynamics and economic conditions. Month-to-month trends highlighted seasonal peaks during high travel periods and declines in months with lower demand. The line chart we’ll design will provide a clear and comprehensive visualization of these price changes over the year.

Visualizing surge in the U.S. gasoline prices in 2024 using React Line Chart

Let’s get started!

Step 1: Collecting gasoline price data

To start, collect reliable data on average monthly gasoline prices for 2024. A good source for this information is the United States Consumer Price Index or other credible databases tracking fuel prices.

In this example, we will analyze the changes in gasoline prices from January to December 2024, highlighting key trends, such as seasonal peaks and economic shifts that influenced the market.

Step 2: Preparing the data for the chart

For a React-based line chart, we need to structure our data as an array of objects. Each object should represent a data point and include fields for the X-axis (e.g., month) and Y-axis (e.g., price).

Refer to the following code example to prepare the data.

export let averagePriceData: Object[] = [
   { month: 'Jan', price: 3.45 },
   { month: 'Feb', price: 3.51 },
   { month: 'Mar', price: 3.55 },
   { month: 'Apr', price: 3.73 },
   { month: 'May', price: 3.68 },
   { month: 'Jun', price: 3.71 },
   { month: 'Jul', price: 3.73 },
   { month: 'Aug', price: 3.95 },
   { month: 'Sep', price: 3.98 },
   { month: 'Oct', price: 3.78 },
   { month: 'Nov', price: 3.50 },
   { month: 'Dec', price: 3.28 }
];
Enter fullscreen mode Exit fullscreen mode

Step 3: Configuring the Syncfusion React Charts

Let’s configure the Syncfusion React Charts control. Refer to the following code example.

<ChartComponent>
 <SeriesCollectionDirective>
  <SeriesDirective></SeriesDirective>
 </SeriesCollectionDirective>
</ChartComponent>
Enter fullscreen mode Exit fullscreen mode

Step 4: Binding gasoline price trends to React Line Chart

Now, we’ll bind the gasoline price data to the React Line Chart using the SeriesDirective. This directive allows you to bind the data source, specify the X and Y values, and customize the chart’s appearance to suit your needs.

<SeriesCollectionDirective>
 <SeriesDirective dataSource={averagePriceData } xName="month" yName="price" type="Line"></SeriesDirective>
</SeriesCollectionDirective>
Enter fullscreen mode Exit fullscreen mode

In this example, the averagePriceData array, which contains monthly gasoline price data, is bound to the dataSource property of the React Line Chart. The month field is mapped to the xName property, and the price field is mapped to the yName property. This configuration ensures that each data point is accurately represented on the chart, providing a clear and effective visualization of gasoline price trends.

Step 5: Customize the React Line Chart appearance

Several elements can be customized to enhance the appearance of the React Line Chart. These include adding a title and subtitle for context, displaying data labels on the line points, adjusting the line style, and incorporating data markers for clarity.

Adding title and subtitle

Refer to the following code to add and customize the title and subtitle of the React Line Chart.

<ChartComponent 
    title="2024 Gas Prices Unveiled" 
    titleStyle={{
        size: '24px', 
        fontWeight: 'bold', 
        textAlignment: 'Near',
    }} 
    subTitle="A Comprehensive Breakdown of Monthly Averages" 
    subTitleStyle={{
        size: '16px', 
        fontWeight: 'normal', 
        color: '#777', 
        textAlignment: 'Near',
    }} 
>
</ChartComponent>
Enter fullscreen mode Exit fullscreen mode

Customizing the chart axes

We can customize the axis lines and ticks using the primaryXAxis and primaryYAxis properties. Additionally, you can style the grid lines with dotted lines by modifying the dashArray property in the majorGridLines. These customization help create a polished and visually distinctive chart.

Refer to the following code example to customize the chart axes and grid lines.

<ChartComponent 
    id="charts" 
    style={{ textAlign: 'center' }} 
    primaryXAxis={{
        valueType: 'Category', 
        majorGridLines: { width: 0 }, 
        majorTickLines: { width: 0 }, 
        lineStyle: { width: 2, color: 'white' } 
    }} 
    primaryYAxis={{
        lineStyle: { width: 0 }, 
        majorTickLines: { width: 0 }, 
        minorTickLines: { width: 0 }, 
        majorGridLines: { dashArray: '5,5' }
    }} 
></ChartComponent>
Enter fullscreen mode Exit fullscreen mode

To highlight the highest price data on the React Line chart, we’ll use strip lines in the primaryXAxis. Strip lines are useful for visually marking specific regions or values on an axis, such as the maximum price point in this case. The stripLines property allows you to define one or more lines that appear across the chart at specific axis values.

Refer to the following code example.

primaryXAxis={{
  stripLines: [
    {
      start: 2.5,
      end: 3.5,
      visible: true,
      color: 'grey',
      opacity: 0.4,
    },
  ],
}}
Enter fullscreen mode Exit fullscreen mode

Customizing data labels and markers

Let’s enhance the readability of the React Line Chart by adding data labels and markers. To display data labels and modify their appearance, we need to enable the visible property in the dataLabel setting within the series configuration.

Refer to the following code example.

<SeriesDirective
  dataSource={averagePriceData}
  xName="month"
  yName="price"
  marker={{
    dataLabel: {
      visible: true,
      format: '${value}',
      font: {
        color: 'black',
        fontWeight: 'bold',
      },
    },
  }}
  type="Line"
/></SeriesDirective>
Enter fullscreen mode Exit fullscreen mode

Next, you can customize the appearance of the markers to enhance visibility and provide a more engaging user experience. Additionally, you can modify the marker style by adjusting the marker property in the series. For more information, refer to the documentation.

marker={{
    visible: true,
    width: 10,
    height: 10,
    shape: 'Circle',
    border: { color: 'black' },
    isFilled: false,
}}
Enter fullscreen mode Exit fullscreen mode

Adding tooltips

Tooltips provide additional details about the specific data point, which can enhance user interaction with the chart. Let’s enable and customize the tooltip, as shown in the following code example.

For more details, refer to the documentation.

tooltip= {{
    enable: true,
    enableHighlight: true,
    format:
        '<b>Average Price of Gasoline over 2024</b><br>${point.x} 2024<br>${point.y} Dollars per Gallon',
}}
Enter fullscreen mode Exit fullscreen mode

Adding annotations

Annotations are an excellent way to highlight specific areas of interest on a chart, such as important data points, trends, or events. Using the annotations option in the React Charts, you can add text, shapes, or even images to the chart. This feature allows you to make the chart more interactive and informative by visually marking key areas of interest. Additionally, you can specify the ID of the element to display within the chart area using the content option of the annotations object.

<AnnotationsDirective>
    <AnnotationDirective
        x="97"
        y="101%"
        region="Chart"
        coordinateUnits="Pixel"
        content="<div style='color:grey;'>Hover over chart to view data</div>"
    >
    </AnnotationDirective>
</AnnotationsDirective>
Enter fullscreen mode Exit fullscreen mode

Customizing the chart area

We can use the chartArea property to enhance the visual appearance of the plot area by customizing the background. You can apply a solid color or gradient to make the chart more visually appealing. This property is particularly useful when you want to highlight the chart area and create a more engaging user experience.

Refer to the following code example.

<ChartComponent chartArea={{ border: { width: 0 }, background: 'url(#gradient)' }}>
</ChartComponent>

<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <linearGradient id="gradient" x1="0%" y1="0%" x2="0%" y2="100%">
      <stop
        offset="0%"
        style={{ stopColor: '#fff8e1', stopOpacity: 1 }}
      />
      <stop
        offset="100%"
        style={{ stopColor: '#f9a825', stopOpacity: 1 }}
       />
    </linearGradient>
  </defs>
</svg>
Enter fullscreen mode Exit fullscreen mode

After executing the above code examples, the output will appear as shown in the following image.

Syncfusion React chart showing the surge in U.S. gasoline prices in 2024

Visualizing the surge in U.S. gasoline prices in 2024 using the React Line Chart

GitHub reference

Also, refer to the visualization of the surge in U.S. gasoline prices using the React Line Chart demo on StackBlitz.

Conclusion

Thanks for reading! In this blog, we’ve explored how to use the Syncfusion React Line Chart to visualize the average price of gasoline in the U.S. in 2024. Similarly, you can visualize other trends and price changes over time. We encourage you to try the steps discussed and share your thoughts in the comments below.

If you require assistance, please don’t hesitate to contact us via our support forum, support portal, or feedback portal. We are always eager to help you!

Related Blogs

Top comments (0)