简体   繁体   中英

How to plot a grouped bar plot from a list of pairs in Python?

I have this list of "coordinates":

   myList = [[0.7366771159874608, 0.6270718232044199], [0.7382352941176471, 0.6710182767624021], [0.7967479674796748, 0.656441717791411], [0.7296511627906976, 0.5727109515260324], [0.7992700729927007, 0.5833333333333334], [0.750788643533123, 0.5288888888888889], [0.851063829787234, 0.7423312883435583], [0.767515923566879, 0.5525114155251142]]

I want to create a grouped bar plot so that each of this pairs is close. The names of the column are just numbered from I to 8. I looked on the internet but it doesn't seem to me other people had this problem.

My code:

import matplotlib.pyplot as plt
x, y = zip(*mylist)
group_labels = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII']
plt.bar(x, y)

plt.title("Trial")
plt.show()

How should I change my dataset in order to achieve my goal?

Adapted from the docs.

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

ar = [[0.7366771159874608, 0.6270718232044199], 
      [0.7382352941176471, 0.6710182767624021], 
      [0.7967479674796748, 0.656441717791411], 
      [0.7296511627906976, 0.5727109515260324], 
      [0.7992700729927007, 0.5833333333333334], 
      [0.750788643533123, 0.5288888888888889], 
      [0.851063829787234, 0.7423312883435583], 
      [0.767515923566879, 0.5525114155251142]
     ]

xx, yy = zip(*ar)
group_labels = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII']
x = np.arange(len(group_labels))
width = 0.35

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, xx, width)
rects2 = ax.bar(x + width/2, yy, width)
ax.set_xticklabels(group_labels)
ax

在此处输入图片说明

As far as I can tell, you are trying to barplot more than one variables in the same barplot. The grouping that you are mentioning can be actually handled as plotting 2 different variables, man and woman.

Unfortunately, this is not natively implemented in matplotlib python, but you can use pandas to achieve the result you want. THe code is

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
myList = [[0.7366771159874608, 0.6270718232044199], [0.7382352941176471, 0.6710182767624021], [0.7967479674796748, 0.656441717791411], [0.7296511627906976, 0.5727109515260324], [0.7992700729927007, 0.5833333333333334], [0.750788643533123, 0.5288888888888889], [0.851063829787234, 0.7423312883435583], [0.767515923566879, 0.5525114155251142]]
x, y = zip(*myList)
group_labels = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII']
df = pd.DataFrame(np.c_[x, y], index=group_labels)
df.plot.bar()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM