python - 在 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 列,但这显然只是给了我这样的结果:
解决方案
当您分散您的点时,您需要确保您正在访问存在的数据框中的 col。在您的代码中,您试图访问一个名为“Year”的列,该列不存在。问题见下:
ax.scatter(df['Price'], df['Level'], s=10, c=df['Year'], marker="o", label=df['Year'], cmap=matplotlib.colors.ListedColormap(colors)
在这行代码中,您指定颜色(c),您正在寻找一个不存在的列。同样,您传入的标签也存在同样的问题。要解决此问题,您需要创建一个包含年份的列:
- 提取所有日期
- 从每个日期仅获取年份
- 将此添加到您的数据框中
下面是一些实现这些步骤的代码:
# 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
推荐阅读
- javascript - 传递一个对象来更新 MongoDB 上的字段
- postgresql - Postgresql 致命:无法创建锁定文件“/var/run/postgresql/.s.PGSQL.5432.lock”:权限被拒绝
- python - 如何在特征工具中为具有相同 id 和时间索引的行创建特征?
- python - 在 Python 中,使用 ruamel.yaml 将字典转储到 Yaml 时如何将字典键值拆分为多行
- c# - 在 TreeView WPF 中显示分层数据
- java - 错误:使用此用户名的用户不存在:使用弹簧安全时
- mobile - 移动设备使用 JMeter 中的 JSR223 请求仿真 - 没有这样的属性:类驱动程序
- html - 我可以计算转换后元素的大小吗?
- flutter - 在 Flutter 中从 AppBar 触发验证/提交表单方法
- ionic-framework - Ionic 6 Oninit 只工作一次