根据分类数据绘制日期时间(Yaxis)

2024-05-14 12:03:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据matplotlib中的一系列datetime值绘制分类信息。如果将分类数据表示为字符串,则可以使绘图正常工作。但是,我希望Y轴是绝对的,这样就可以按正确的顺序进行排序。你知道吗

下面的代码段显示了我到目前为止所做的工作。在绘图中,将y替换为y_cat,然后matplotlib抛出错误:

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轴上有评论分类的图表,从最好到最差,从上到下排序


Tags: importformatmatplotlibas分类pltlabelcat
1条回答
网友
1楼 · 发布于 2024-05-14 12:03:55

您将它们作为list传递,而它期望的是tuple。以下代码已更正:

已编辑:如果还希望在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

相关问题 更多 >

    热门问题