简体   繁体   English

如何从 Python 中的对列表绘制分组条形图?

[英]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.列的名称只是从 I 到 8 编号。我在互联网上查看,但在我看来其他人没有这个问题。

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.您提到的分组实际上可以作为绘制 2 个不同的变量(男人和女人)来处理。

Unfortunately, this is not natively implemented in matplotlib python, but you can use pandas to achieve the result you want.不幸的是,这不是在 matplotlib python 中本地实现的,但是您可以使用 Pandas 来实现您想要的结果。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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