There's more...

There are a bunch of different charts that can be created, including bar charts, line charts, area charts (line charts that fill the area between the line and the axis), pie charts, or scatter charts (XY charts where one value is plotted against the other). Each kind of chart has an equivalent class, for example PieChart or LineChart.

Each one, at the same time, can have different types. For example, the default type for BarChart is column, printing the bars vertically, but they can also be printed in vertical, selecting a different type:

>>> chart.type = 'bar'

Check the openpyxl documentation to see all available combinations.

Instead of extracting the axis labels from the data, they can be set explicitly with set_categories. For example, compare step 4 with the following code:

data = Reference(sheet, min_row=2, max_row=4, min_col=2, max_col=2)
labels = Reference(sheet, min_row=2, max_row=4, min_col=1, max_col=1)
chart.add_data(data, from_rows=False, titles_from_data=False)
chart.set_categories(labels)

The range, instead of using a Reference object, can also be input with text labels describing the region:

chart.add_data('Sheet!B2:B4', from_rows=False, titles_from_data=False)
chart.set_categories('Sheet!A2:A4')

This way of describing it may be more difficult to deal with if the range of data needs to be created programatically.

Defining charts in Excel correctly can be difficult sometimes. The way Excel extracts the data from a particular range can be baffling. Remember to allow time for trial and error, and to deal with differences. For example, in step 4 we define three series with one data point, while in the preceding code we define a single series with three data points. Most of those differences are subtle. Finally, the most important point is how the end chart looks. Try different chart types and learn the differences.

The full openpyxl documentation can be found here:

https://openpyxl.readthedocs.io/en/stable/index.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.109.92