python - 图例颜色与 seaborn 不匹配
问题描述
我正在使用 sns.pointplot 并且由于没有label
属性,我决定创建我的自定义图例,但我的问题是颜色不匹配。
我的数据框如下所示:
deploy deployed_today_rent total_rent cum_deploy hourly percent cum_percent
10min
2019-10-01 05:30:00 6 0 0 6 0.000000 0.000000
2019-10-01 05:40:00 0 0 0 6 0.000000 0.000000
2019-10-01 05:50:00 6 0 0 12 0.000000 0.000000
2019-10-01 06:00:00 13 0 0 25 0.000000 0.000000
2019-10-01 06:10:00 0 0 0 25 0.000000 0.000000
2019-10-01 06:20:00 0 1 1 25 0.040000 0.040000
2019-10-01 06:30:00 0 0 0 25 0.000000 0.040000
2019-10-01 06:40:00 0 1 1 25 0.040000 0.080000
2019-10-01 06:50:00 1 1 1 26 0.038462 0.118462
fig,(ax1)= plt.subplots(nrows=1)
fig.set_size_inches(22,17)
sns.pointplot(data=test, x=test.index, y="total_rent", ax=ax1,color="blue", label="total")
sns.pointplot(data=test, x=test.index, y="deployed_today_rent", ax=ax1, color="green", label="deployed_rent")
sns.pointplot(data=test, x=test.index, y="cum_deploy", ax=ax1, color="#BEC647", label="cum_deploy")
ax1.legend(labels=["total", "deployed_rent", "cum_deploy"], fontsize=15)
plt.savefig("test.png", dpi=300, bbox_inches="tight");
它成功创建了一个图例,但是图例中的颜色与线条不匹配。
解决方案
从图例指南中,您可以通过为每行创建一个“代理艺术家”来做到这一点,matplotlib.lines.Line2D
就像这样
from matplotlib.lines import Line2D
a = Line2D([], [], color=‘blue’, label=‘total’)
b = Line2D([], [], color=‘green’, label=‘deployed_rent’)
c = Line2D([], [], color=‘#BEC647’, label=‘cum_deploy’)
plt.legend(handles=[a, b, c])
这应该产生一个具有默认宽度的三种不同颜色线及其各自标签的图例。
推荐阅读
- specflow - 我可以让 BeforeScenario 和 AfterScenario 挂钩中的场景失败吗?
- swift - 我的函数在里面的数据被处理返回之前返回
- python-3.x - KeyError:使用 API 将数据插入数据库
- reactjs - 更改 jwt 令牌的 Apollo 客户端选项
- maven - Automation of release and dependency management
- logstash - Logstash - 如何用逗号分割数组?
- python - 我无法在 Python (PyCharm) 中输入字母“&”它用空格 {BUG} 替换它
- javascript - 如何将对话框中的用户输入数据保存到隐藏字段中:Jquery 和 HTML
- javascript - 使用 foreach 更新数组的特定列键的每个值
- css - 如何更改字体真棒图标的颜色