pandas 更改 Matplotlib 图表 X 轴上的顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47255746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change Order on X-Axis for Matplotlib chart
提问by user8659376
I created a chart in matplotlib using python and the x-axis is the days of the week (Mon-Sun). When the data was plotted though, the x-axis is not arranged Mon-Sun.
我使用 python 在 matplotlib 中创建了一个图表,x 轴是一周中的几天(周一至周日)。但是,绘制数据时,x 轴并未排列在周一至周日。
Is there way I can re-order the x-axis to have it be formatted this way?
有什么方法可以重新排序 x 轴以使其格式化?
or is there a way I can re-order the dataset? It is a csv file that is being read using the panda dataframe
或者有什么方法可以重新排序数据集?这是一个使用Pandas数据框读取的 csv 文件
Example Data: (lives in csv: './data/Days_Summary.csv')
示例数据:(存在于 csv 中:'./data/Days_Summary.csv')
Day Value
Monday 56
Tuesday 23
Wednesday 34
Thursday 56
Friday 58
Saturday 70
Sunday 43
Code:
代码:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.read_csv('./data/Days_Summary.csv')
days_values=df.groupby(['day'])['day'].count().plot(kind='bar')
plt.xlabel('Day')
plt.ylabel('Values')
plt.show()
回答by andrew_reece
Use .loc
to set the day order:
使用.loc
设置天阶:
field = "Day"
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
ax = df.set_index(field).loc[day_order].plot(kind="bar", legend=False)
ax.set_ylabel("Value")
Note: Using groupby()
and count()
will not give you the values in the Value
field, but will instead count the number of rows in each group. In this case, you'll just get a count of 1 for each day. Hence this answer assumes that
you actually want to plot the values in Value
for each day.
注意:使用groupby()
和count()
不会为您提供Value
字段中的值,而是会计算每组中的行数。在这种情况下,您每天只会得到 1 的计数。因此,这个答案假设您实际上想要绘制Value
每天的值。