How to create a bar chart and save in pptx using Python?

How to create a bar chart and save in pptx using Python?

Creating a bar chart and saving it into a PowerPoint presentation using Python can be done by combining several libraries. You will typically use matplotlib or plotly to create the chart, and python-pptx to handle the PowerPoint (.pptx) part. Below is a step-by-step guide on how to accomplish this.

Step 1: Install Required Libraries

First, you need to install the matplotlib, python-pptx, and Pillow libraries, if you haven't already. You can install them using pip:

pip install matplotlib python-pptx Pillow 

Step 2: Create a Bar Chart using Matplotlib

Here is an example of creating a simple bar chart with matplotlib:

import matplotlib.pyplot as plt # Sample data categories = ['Category A', 'Category B', 'Category C'] values = [3, 7, 2] # Create a bar chart plt.figure(figsize=(8, 6)) plt.bar(categories, values, color='skyblue') plt.title('Sample Bar Chart') plt.xlabel('Categories') plt.ylabel('Values') # Save the chart as an image file plt.savefig('bar_chart.png') plt.close() 

This code will create a bar chart and save it as bar_chart.png in the current directory.

Step 3: Add the Chart Image to a PowerPoint Slide

Now you can use python-pptx to create a PowerPoint presentation and insert the chart image into a slide:

from pptx import Presentation from pptx.util import Inches # Create a presentation object prs = Presentation() # Define the layout. 5 is usually the title and content layout. slide_layout = prs.slide_layouts[5] # Add a slide slide = prs.slides.add_slide(slide_layout) # Set title for the slide title = slide.shapes.title title.text = "Bar Chart Example" # Add the saved image to the slide img_path = 'bar_chart.png' left = Inches(1) # 1 inch from the left edge top = Inches(1.5) # 1.5 inches from the top height = Inches(4.5) # height of the image # Add picture to slide slide.shapes.add_picture(img_path, left, top, height=height) # Save the presentation prs.save('chart_presentation.pptx') 

The python-pptx library can be a bit particular about image file formats and may sometimes throw an error if the image is not in a format it expects. The Pillow library (PIL fork) is used internally to handle images, so ensure your image is in a common format like PNG or JPEG.

This code will create a new PowerPoint file named chart_presentation.pptx with one slide containing the bar chart image and a title.

Remember that this is just a basic example. Both matplotlib and python-pptx offer extensive customization options for creating more complex and styled charts and presentations.


More Tags

mouse-position aggregate pywin32 console-application custom-post-type jquery-steps dynamic-resizing curve-fitting responsive-design scheme

More Programming Guides

Other Guides

More Programming Examples