简体   繁体   English

更改 Matplotlib 图表 X 轴上的顺序

[英]Change Order on X-Axis for Matplotlib chart

I created a chart in matplotlib using python and the x-axis is the days of the week (Mon-Sun).我使用 python 在 matplotlib 中创建了一个图表,x 轴是一周中的几天(周一至周日)。 When the data was plotted though, the x-axis is not arranged Mon-Sun.但是,在绘制数据时,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这是一个使用熊猫数据框读取的 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()

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.注意:使用groupby()count()不会为您提供Value字段中的Value ,而是会计算每个组中的行数。 In this case, you'll just get a count of 1 for each day.在这种情况下,您每天只会得到 1 的计数。 Hence this answer assumes that you actually want to plot the values in Value for each day.因此,此答案假定您实际上想要绘制每天的Value

For application on Seaborn.适用于 Seaborn。 You can do this using count plot https://seaborn.pydata.org/generated/seaborn.countplot.html您可以使用计数图https://seaborn.pydata.org/generated/seaborn.countplot.html

day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
sns.countplot(x = "Day", data = df, order = day_order)

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

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