SoFunction
Updated on 2024-11-13

Python Plotting Bar Charts Stacked Charts Full Code

I. Introduction of libraries

import  as plt
import numpy as np

II. Data preparation

Example: pandas is a tool based on NumPy that was created to solve data analysis tasks.

Before we start plotting the bar stacked graph, we need to generate the experimental data. In this case, we can use the NumPy library to generate two arrays y1 and y2 to represent the sales of products A and B in five different cities. The code is as follows:

import numpy as np
# Generate experimental data
x = (['A', 'B', 'C', 'D', 'E'])
y1 = ([12, 25, 19, 23, 20])
y2 = ([15, 24, 25, 18, 20])

III. Plotting basic bar stacks

1. Drawing basic shapes

Use Matplotlib's bar function to plot a bar stacked plot. The function needs to be passed the following arguments:

  • left: the position of the left side of each rectangle bar;
  • height: the height of each rectangle bar;
  • bottom: the position of the bottom edge of each rectangle bar, i.e. the position of the top of the previous rectangle bar;
  • width: the width of each rectangle, defaults to 0.8.

Two arrays y1 and y2 are used to represent the sales of products A and B in five cities respectively, and an array of x is used to represent the name of each city. We start by defining a plotting parameter for the bar chart with the following code:

# Set the font style and size
font={'family':'Times New Roman','size':28}
font_value = {'family':'Times New Roman','size':20}
# Draw column stacks, set column colors and labels
fig, ax = (figsize=(12, 8))
N = len(y1)
width = 0.45
ind = (N)
bar_plot1 = (ind, y1, width, color=.Set1((N)), alpha=0.7, label='Type A')
bar_plot2 = (ind, y2, width, bottom=y1, color=.Set2((N)), alpha=0.7, label='Type B')

2. Set the column width, add scale labels and rotation angle

Adjust the width of the columns so that there is more distance between them in order to more clearly distinguish the sales in each city.

The width of the column can be adjusted using the width parameter, e.g. width=0.4. Additionally, we need to add scale labels to the horizontal axis and rotate the labels by 45 degrees to show the name of each city more clearly. The code is as follows:

# Set the font style and size
font={'family':'Times New Roman','size':28}
font_value = {'family':'Times New Roman','size':20}
# Draw column stacks, set column colors and labels
fig, ax = (figsize=(12, 8))
N = len(y1)
width = 0.45
ind = (N)
bar_plot1 = (ind, y1, width, color=.Set1((N)), alpha=0.7, label='Type A')
bar_plot2 = (ind, y2, width, bottom=y1, color=.Set2((N)), alpha=0.7, label='Type B')
# Add titles, labels and legends
ax.set_title('Sales of Product A & B in Different Cities', fontsize=24)
ax.set_xlabel('City', font)
ax.set_ylabel('Value', font)
(ncol=2, loc='best', fontsize=20)
# Set the horizontal axis scale label rotation angle
new_x = ['City '+i for i in x]
((len(x)), new_x, rotation=45)
# Show charts
()

IV. Complete code

import  as plt
import numpy as np
# Generate experimental data
x = (['A', 'B', 'C', 'D', 'E'])
y1 = ([12, 25, 19, 23, 20])
y2 = ([15, 24, 25, 18, 20])
# Set the font style and size
font={'family':'Times New Roman','size':28}
font_value = {'family':'Times New Roman','size':2}
# Draw column stacks, set column colors and labels
fig, ax = (figsize=(12, 8))
# of groups of columns defining the plot
N = len(x)
### Setting the column width
width = 0.45
ind = (N)
bar_plot1 = (ind, y1, width, color=.Set1((N)), alpha=0.7, label='Type A')
bar_plot2 = (ind, y2, width, bottom=y1, color=.Set2((N)), alpha=0.7, label='Type B')
# bar_plot3 = bar_plot2+bar_plot
# Add titles, labels and legends
# ax.set_title('Temperature / ℃', fontsize=24)
ax.set_xlabel('City', font)
ax.set_ylabel('Value', font)
(ncol=2, loc='best', fontsize=20)
ax.set_ylim(0,53)
## x-axis scale name, tilt angle
new_x = ['City '+i for i in x]
((len(x)), new_x, rotation=45)
# Setting the axis scale font and font size
font_tick = {'family': 'Times New Roman', 'size': 24}
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontproperties(font_tick)
# Adjust other parameters such as font color, column width, etc.
for rect, height_1, height_2 in zip(bar_plot2, y1, y2):
    height_2 = rect.get_height()
    (rect.get_x() + rect.get_width()/2., height_1 + height_2 + 0.5, '%d' % int(height_2),
            ha='center', va='bottom', fontsize=20, color='green', fontname='Times New Roman')
    (rect.get_x() + rect.get_width()/2., height_1 + 1/2, '%d' % int(height_1),
            ha='center', va='bottom', fontsize=20, color='blue', fontname='Times New Roman')
## whether the upper right border is visible or not
# ['top'].set_visible(False)
# ['right'].set_visible(False)
## Scale line length and width settings
ax.tick_params(axis='x', direction='out', length=6, width=2)
ax.tick_params(axis='y', direction='in', length=6, width=2)
plt.tight_layout()
("C:/Users/ypzhao/Desktop/",dpi=600)
# Show charts
()

V. Operational results

summarize

To this article on Python draw a bar chart stacked graphs are introduced to this article, more related Python draw a bar chart stacked graphs content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!