How to create a figure of subplots of grouped bar charts in python

2024/9/27 17:27:06

I want to combine multiple grouped bar charts into one figure, as the image below shows. grouped bar charts in a single figure

import matplotlib
import matplotlib.pyplot as plt
import numpy as nplabels = ['G1', 'G2', 'G3']
yesterday_test1_mean = [20, 12, 23]
yesterday_test2_mean = [21, 14, 25]
today_test1_mean = [18, 10, 12]
today_test2_mean = [13, 13, 9]

Firstly I created each grouped bar chart by plt.subplots()

x = np.arange(len(labels))
width = 0.3fig1, ax = plt.subplots()
rects1 = ax.bar(x-width/2, yesterday_test1_mean, width)
rects2 = ax.bar(x+width/2, yesterday_test2_mean, width)fig2, ax = plt.subplots()
rects3 = ax.bar(x-width/2, today_test1_mean, width)
rects4 = ax.bar(x+width/2, today_test2_mean, width)

Then, I used add_subplot in an attempt to treat fig1 and fig2 as new axes in a new figure.

fig_all = plt.figure()
fig1 = fig_all.add_subplot(1,2,1)
fig2 = fig_all.add_subplot(1,2,2)
fig_all.tight_layout()
plt.show()

But it didn't work. How can I combined several grouped bar charts into a single figure?

Thanks in advance.

Answer

Well, I tried something. Here's a rough result. Only thing I changed is that rather using axes, I am just using subplot as I learned over time. So with fig and axes as output, there must be a way too. But this is all I've ever used. I've not added the legend and title yet, but I guess you can try it on your own too.

Here's the code with just small change:

import matplotlib.pyplot as plt
import numpy as nplabels = ['G1', 'G2', 'G3']
yesterday_test1_mean = [20, 12, 23]
yesterday_test2_mean = [21, 14, 25]
today_test1_mean = [18, 10, 12]
today_test2_mean = [13, 13, 9]x = np.arange(len(labels))
width = 0.3plt.figure(figsize=(12,5))plt.subplot(121)
plt.bar(x-width/2, yesterday_test1_mean, width)
plt.bar(x+width/2, yesterday_test2_mean, width)    plt.subplot(122)
plt.bar(x-width/2, today_test1_mean, width)
plt.bar(x+width/2, today_test2_mean, width)plt.show()

And here's your initial result: enter image description here

While you see the result and try some stuff on your own, let me try to add the labels and legend to it as well as you've provided in the sample image.

Edit: The final output

So here it is, the exact thing you're looking for:

enter image description here

Code: import matplotlib.pyplot as plt import numpy as np

labels = ['G1', 'G2', 'G3']
yesterday_test1_mean = [20, 12, 23]
yesterday_test2_mean = [21, 14, 25]
today_test1_mean = [18, 10, 12]
today_test2_mean = [13, 13, 9]x = np.arange(len(labels))
width = 0.3plt.figure(figsize=(12,5))plt.subplot(121)
plt.title('Yesterday', fontsize=18)
plt.bar(x-width/2, yesterday_test1_mean, width, label='test1', hatch='//', color=np.array((199, 66, 92))/255)
plt.bar(x+width/2, yesterday_test2_mean, width, label='test2', color=np.array((240, 140, 58))/255)
plt.xticks([0,1,2], labels, fontsize=15)plt.subplot(122)
plt.title('Today', fontsize=18)
plt.bar(x-width/2, today_test1_mean, width, hatch='//', color=np.array((199, 66, 92))/255)
plt.bar(x+width/2, today_test2_mean, width, color=np.array((240, 140, 58))/255)
plt.xticks([0,1,2], labels, fontsize=15)plt.figlegend(loc='upper right', ncol=1, labelspacing=0.5, fontsize=14, bbox_to_anchor=(1.11, 0.9))
plt.tight_layout(w_pad=6)
plt.show()
https://en.xdnf.cn/q/71439.html

Related Q&A

Python Pillow: Make image progressive before sending to 3rd party server

I have an image that I am uploading using Django Forms, and its available in the variable as InMemoryFile What I want to do is to make it progressive.Code to make an image a progressiveimg = Image.open…

Python - Should one start a new project directly in Python 3.x?

What Python version can you please recommend for a long-term (years) project? Should one use 2.6+ or 3.x is already stable? (only standard libraries are required)UPDATE: according to the answers belo…

Produce random wavefunction

I need to produce a random curve in matplotlib.My x values are from say 1 to 1000 for example. I dont want to generate scattered random y values, I need a smooth curve. Like some kind of very distorted…

How to reference groupby index when using apply, transform, agg - Python Pandas?

To be concrete, say we have two DataFrames:df1:date A 0 12/1/14 3 1 12/1/14 1 2 12/3/14 2 3 12/3/14 3 4 12/3/14 4 5 12/6/14 5df2:B 12/1/14 10 12/2/14 20 12/3/14 10 12/4/14 30 12/5/14 10 …

Google AppEngine Endpoints Error: Fetching service config failed (status code 404)

I am implementing the steps in the Quickstart.I did notice another question on this. I double checked that env_variables section in app.yaml has the right values for ENDPOINTS_SERVICE_NAME and ENDPOIN…

How to unload a .NET assembly reference in IronPython

After loading a reference to an assembly with something like:import clr clr.AddRferenceToFileAndPath(rC:\foo.dll)How can I unload the assembly again?Why would anyone ever want to do this? Because Im …

Bad key axes.prop_cycle Error while using an mplstyle in matplotlib (Python)

I am getting the following error when I try to use an external style sheet loaded locally. Bad key "axes.prop_cycle" on line 270 in idt.mplstyle. You probably need to get an updated matplotli…

Dollar notation in script languages - why? [closed]

Closed. This question is off-topic. It is not currently accepting answers.Want to improve this question? Update the question so its on-topic for Stack Overflow.Closed 12 years ago.Improve this questio…

Failure to build wheel / Error: INCLUDE Environment Variable is empty

I am using Python 2.7.11 and am trying to pip install modules however a few of them are failing. The message I get is "Failure to build wheel for X" and "Error: INCLUDE Environment Varia…

Calculating the position of QR Code alignment patterns

I need to know how to calculate the positions of the QR Code alignment patterns as defined in the table of ISO/IEC 18004:2000 Annex E.I dont understand how its calculated. If you take the Version 16, f…