Matplotlib图表在X轴上的更改顺序 [英] Change Order on X-Axis for Matplotlib chart

查看:45
本文介绍了Matplotlib图表在X轴上的更改顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 python 在 matplotlib 中创建了一个图表,x 轴是一周中的天数(周一至周日).但是,在绘制数据时,x 轴并未排列在周一至周日.

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.

有什么办法可以重新排列 x 轴的格式,使其按这种方式格式化吗?

Is there way I can re-order the x-axis to have it be formatted this way?

或者有什么方法可以重新排序数据集?这是一个正在使用熊猫数据框读取的 csv 文件

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中:"./data/Days_Summary.csv")

Example Data: (lives in csv: './data/Days_Summary.csv')

Day         Value

 Monday      56        
 Tuesday     23    
 Wednesday   34     
 Thursday     56     
  Friday      58     
 Saturday     70      
  Sunday      43      

代码:

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()

推荐答案

使用 .loc 设置日期顺序:

Use .loc to set the day order:

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")

注意:使用 groupby() count()不会为您提供 Value 字段中的值,而是计算每组中的行数.在这种情况下,您每天只会得到 1 的计数.因此,这个答案假设您实际上是想每天绘制 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.

这篇关于Matplotlib图表在X轴上的更改顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆