首页 > 解决方案 > 使用 Panda 和 Matplotlib 绘制一个组

问题描述

我想使用 Panda 和 Matplotlib 作为一个组进行绘图。情节看起来像这种分组:

在此处输入图像描述

现在假设我有一个数据文件 example.csv:

first,second,third,fourth,fifth,sixth
-42,11,3,La_c-,D
-42,21,2,La_c-,D0
-42,31,2,La_c-,D
-42,122,3,La_c-,L

print(df.head())以上是:

   first   second   third  fourth  fifth   sixth
0    -42       11       3   La_c-      D     NaN
1    -42       21       2   La_c-     D0     NaN
2    -42       31       2   La_c-      D     NaN
3    -42      122       3   La_c-      L     NaN

在我的例子中,在 x 轴上,每个组将由(第一列和第二列)组成,就像在上面的图中它们有 pies_2018、pies_2019、pies_2020。

为此,我尝试先绘制一列:

 #!/usr/bin/env python3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

    #from scipy import stats
    #import ast
    filename = 'example.csv'
    df = pd.read_csv(filename)
    print(df.head())
    df.plot(kind='bar', x=df.columns[1],y=df.columns[2],figsize=(12, 4))
    plt.gcf().subplots_adjust(bottom=0.35)

我得到这样的情节:

在此处输入图像描述

现在的问题是,当我想创建一个组时,我收到以下错误:

     raise ValueError("x must be a label or position")
ValueError: x must be a label or position

问题是我将数字视为标签。

我使用的代码:

#!/usr/bin/env python3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

#from scipy import stats
#import ast
filename = 'example.csv'
df = pd.read_csv(filename)
print(df.head())
df.plot(kind='bar', x=["first", "second"],y="third",figsize=(12, 4))
plt.gcf().subplots_adjust(bottom=0.35)
plt.xticks(rotation=90)

如果我可以将第一个和第二个绘制为一组,除了图例之外,我还想提到“第一”栏中的第五列和“第二”栏中的第六列。

标签: pythonpandasdataframematplotlib

解决方案


尝试这个。你可以到处玩,但这会给你成组的堆叠条。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

first = [-42, -42, -42, -42] #Use your column df['first']
second = [11, 21, 31, 122] #Use your column df['second']
third = [3, 2, 2, 3]
x = np.arange(len(third))
width = 0.25  #bar width

fig, ax = plt.subplots()
bar1 = ax.bar(x, third, width, label='first', color='blue')
bar2 = ax.bar(x + width, third, width, label='second', color='green')
ax.set_ylabel('third')
ax.set_xticks(x)
rects = ax.patches
labels = [str(i) for i in zip(first, second)] #You could use the columns df['first'] instead of the lists

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width() / 2, height, label,
            ha='center', va='bottom')
ax.legend()

编辑和新的情节 -

在此处输入图像描述


推荐阅读