gpt4 book ai didi

python - 根据分类数据绘制日期时间(Y 轴)

转载 作者:行者123 更新时间:2023-12-05 05:09:42 24 4
gpt4 key购买 nike

我正在尝试根据 matplotlib 中的一系列 datetime 值绘制分类信息。如果分类数据表示为字符串,我就可以让绘图起作用。但是,我希望 Y 轴是分类的,以便可以按正确的顺序对其进行排序。

下面的代码段显示了我到目前为止的内容。在图中,将y替换为y_catmatplotlib会抛出错误:

import pandas as pd
import numpy as np
import calendar, datetime

import matplotlib as mpl
import matplotlib.pyplot as plt

# %matplotlib inline #for Jupyter notebooks

x = pd.date_range('2015/08/01', freq='4M', periods=9)
y = pd.Series(['Good', 'Very Good', 'Very Good', 'Average', 'Average', 'Good', 'Excellent', 'Excellent', 'Excellent'])
y_cat = pd.Categorical(y, categories=['Poor', 'Average', 'Good', 'Very Good', 'Excellent'], ordered=True)

fig, currAX = plt.subplots(figsize=(10, 4))
label_format = {'fontsize':12, 'fontweight':'bold'}
title_format = {'fontsize':15, 'fontweight':'bold'}

currAX.plot(x, y, color='crimson', linestyle='-')
#uncomment for error
#currAX.plot(x, y_cat, color='crimson', linestyle='-')

currAX.xaxis.set_major_formatter(mpl.dates.DateFormatter('%Y %b'))

currAX.spines['top'].set_visible(False)
currAX.spines['right'].set_visible(False)
currAX.spines['left'].set_visible(False)

currAX.set_xlabel('Review Period', **label_format)
currAX.set_ylabel('Review Rating', **label_format)

fig.tight_layout()
plt.show();

### ERROR:
IndexError: tuple index out of range

我想在 Y 轴上查看评论类别的图表,从最好到最差,从上到下排序

最佳答案

当它需要一个 tuple 时,您将它们作为 list 传递。这里的代码更正:

已编辑:如果您还想在 Y 轴上排序值,则需要指定一个数值,以便绘图知道每个点的放置位置。然后用您的标签替换 INT 值。这里是更新的代码。

import pandas as pd
import numpy as np
import calendar, datetime

import matplotlib as mpl
import matplotlib.pyplot as plt

# %matplotlib inline #for Jupyter notebooks


x = pd.date_range('2015/08/01', freq='4M', periods=9).tolist()
y = pd.Series(['Good', 'Very Good', 'Very Good', 'Average', 'Average', 'Good', 'Excellent', 'Poor', 'Excellent']).tolist()


### create a conversion DICT
conversion = { \
"Poor" : 0, \
"Average" : 1, \
"Good" : 2, \
"Very Good" : 3, \
"Excellent" : 4 \
}
## open a list and insert in it the INT corresponding value
y_converted = []
for v in y :
y_converted.append(conversion[v])

fig, currAX = plt.subplots(figsize=(10, 4))
label_format = {'fontsize':12, 'fontweight':'bold'}
title_format = {'fontsize':15, 'fontweight':'bold'}

### pass as tuple
currAX.plot(x, y_converted, color='crimson', linestyle='-')


currAX.xaxis.set_major_formatter(mpl.dates.DateFormatter('%Y %b'))

currAX.spines['top'].set_visible(False)
currAX.spines['right'].set_visible(False)
currAX.spines['left'].set_visible(False)

currAX.set_xlabel('Review Period', **label_format)
currAX.set_ylabel('Review Rating', **label_format)

### tell matplotlib the ticks and labels to use on Y-axis
currAX.set_yticks( list(conversion.values()) )
currAX.set_yticklabels( list(conversion.keys()) )

fig.tight_layout()
plt.show();

结果: enter image description here

关于python - 根据分类数据绘制日期时间(Y 轴),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57329903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com