首页 > 解决方案 > 如何通过对列进行分组来绘制 Python 中的数据框?

问题描述

我有一个这样的数据框: 在此处输入图像描述

我想按目的地对其进行分组,并按条形图绘制旅行者的排序值。现在我的问题:我用过o1_p1.groupby(by = "Destination").sum().plot(legend=True,kind = 'bar')

我得到了这种不清楚的情节! 在此处输入图像描述

第二个问题如何对 X 轴进行排序?

标签: pythonpandasdataframeplotpandas-groupby

解决方案


计算后sort_values()

s = 50
df = pd.DataFrame({"Destination":np.random.randint(1,20, s)
              ,"Travellers":np.random.randint(300,10000, s)
             })

df.groupby(by = "Destination").sum().sort_values("Travellers").plot(legend=True,kind = 'bar')

在此处输入图像描述

自定义 x 轴

您可以更改许多参数,查看matplotlib文档。下面演示先创建图形和轴,pandas plot()然后根据需要更改使用。

import matplotlib.pyplot as plt

s = 150
df = pd.DataFrame({"Destination":np.random.randint(1,50, s)
              ,"Travellers":np.random.randint(300,10000, s)
             })

# create figure and axis so that parameters can be changed
fig, ax = plt.subplots(figsize=[10,6])
df.groupby(by = "Destination").sum().sort_values("Travellers").plot(ax=ax, legend=True,kind = 'bar')
# bold the text
ax.set_xlabel(ax.xaxis.get_label().get_text(), weight='bold', fontsize=12)
# show every second label to prevent conjection...
for label in ax.xaxis.get_ticklabels()[::2]: label.set_visible(False)


推荐阅读