将日期时间绘制在分类数据(Y轴)上

3

我正在尝试在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轴上排序,从最好到最差,从上到下。

1个回答

2
你正在传递一个列表给它期望的元组。下面是更正后的代码:

编辑:如果你想在Y轴上有排序值,需要指定一个数字值,以便图表知道在哪里放置每个点。然后用你的标签替换整数值。下面是更新后的代码。

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

结果: 这里输入图片描述
最初的回答已被翻译成中文。

元组肯定能让你绘制图形。有没有一种方法可以按类别顺序对Y轴进行排序?我尝试在plot调用期间对其进行排序,但那样做并没有起作用。 - Anandologist
我已经根据您的要求编辑了我的答案,请考虑接受并点赞。 - cccnrc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接