Skip to main content
Practice

Creating Charts and Visualizing Data with Python

Charts help to visualize data and make it easily understandable.

The python-pptx library allows you to create various types of charts and visualize data effectively.

In this lesson, we will look at how to create charts, add data, and set formatting using a bar chart as an example.


Understanding and Creating Different Types of Charts

python-pptx supports various types of charts such as bar charts, pie charts, and line charts.

Let's take a look at how to create a basic bar chart, which is one of the fundamental types of charts.


Example of Creating a Bar Chart

Bar charts are useful for comparing the size of data across different categories.

Here is a simple code example to create a bar chart.

Creating a Bar Chart
# Prepare chart data
chart_data = CategoryChartData()

# Add categories (horizontal axis)
chart_data.categories = ['Category 1', 'Category 2', 'Category 3']

# Add a data series (vertical axis)
chart_data.add_series('Series 1', (1.2, 2.3, 3.4))

# Set chart position and size
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)

# Create a vertical bar chart
chart = slide.shapes.add_chart(
XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data
).chart

Code Explanation

  • Creating a Presentation : Creates a new presentation object with Presentation().

  • Adding a Slide : Adds a slide to the presentation using the add_slide() method.

  • Preparing Chart Data : Prepares the data for the chart using a CategoryChartData() object.

  • Adding Categories : Adds categories using chart_data.categories. Categories are the values displayed on the horizontal axis of the chart.

  • Adding Data Series : Adds a data series using chart_data.add_series(). Data series are the values displayed on the vertical axis of the chart.

  • Inserting a Chart : Inserts the chart into the slide using the add_chart() method. Creates a vertical bar chart with XL_CHART_TYPE.COLUMN_CLUSTERED.

  • Creating a Bar Chart : Creates a bar chart with XL_CHART_TYPE.COLUMN_CLUSTERED.


  • chart.has_legend = True : Displays the chart legend (data labels).

  • chart.value_axis.has_major_gridlines = False : Does not display major gridlines for the vertical axis.


Creating Other Types of Charts

In addition to bar charts, you can create various other types of charts using Python.

  • Pie Chart : XL_CHART_TYPE.PIE

  • Line Chart : XL_CHART_TYPE.LINE

  • Area Chart : XL_CHART_TYPE.AREA

For example, to create an area chart using the same code, change the first argument of the add_chart() method to XL_CHART_TYPE.AREA.

Creating an Area Chart
chart = slide.shapes.add_chart(
XL_CHART_TYPE.AREA, x, y, cx, cy, chart_data
).chart

For more information on different types of charts and formatting options, please refer to the official documentation of python-pptx.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.