首页 > 解决方案 > 在 Python 列中基于年份创建标签

问题描述

我制作了一个包含日期和 2 个值的数据框,如下所示:

Date          Year        Level        Price
2008-01-01    2008        56           11
2008-01-03    2008        10           12
2008-01-05    2008        52           13
2008-02-01    2008        66           14
2008-05-01    2008        20           10
..
2009-01-01    2009        12           11
2009-02-01    2009        70           11
2009-02-05    2009        56           12
..
2018-01-01    2018        56           10
2018-01-11    2018        10           17
..

我可以通过在他们的年份上创建一个列来按颜色在他们的年份上绘制这些图,df['Year'] = df['Date'].dt.year但我还希望在图例中的每一年都有标签。

我现在按年份绘制的代码如下所示:

colors = ['turquoise','orange','red','mediumblue', 'orchid', 'limegreen']

fig = plt.figure(figsize=(15,10))
ax = fig.add_subplot(111)

ax.scatter(df['Price'], df['Level'], s=10, c=df['Year'], marker="o", label=df['Year'], cmap=matplotlib.colors.ListedColormap(colors))
plt.title('Title', fontsize=16)
plt.ylabel('Level', fontsize=14)
plt.xlabel('Price', fontsize=14)
plt.legend(loc='upper left', prop={'size': 12});
plt.show()

如何调整图例中的标签以显示年份?我这样做的方式只是使用 Year 列,但这显然只是给了我这样的结果:

在此处输入图像描述

标签: pythonpython-3.xpandasdataframematplotlib

解决方案


当您分散您的点时,您需要确保您正在访问存在的数据框中的 col。在您的代码中,您试图访问一个名为“Year”的列,该列不存在。问题见下:

ax.scatter(df['Price'], df['Level'], s=10, c=df['Year'], marker="o", label=df['Year'], cmap=matplotlib.colors.ListedColormap(colors)

在这行代码中,您指定颜色(c),您正在寻找一个不存在的列。同样,您传入的标签也存在同样的问题。要解决此问题,您需要创建一个包含年份的列:

  1. 提取所有日期
  2. 从每个日期仅获取年份
  3. 将此添加到您的数据框中

下面是一些实现这些步骤的代码:

# Create a list of all the dates
dates = df.Date.values

#Create a list of all of the years using list comprehension
years = [x[0] for x in dates.split('-')]

# Add this column to your dataframe
df['Year'] = years

同样,我会指导您学习本课程以了解有关在 python 中绘图的更多信息! https://exlskills.com/learn-en/courses/python-data-modeling-intro-for-machine-learning-python_modeling_for_machine_learning/content


推荐阅读