【发布时间】:2021-08-11 05:13:07
【问题描述】:
我正在使用 Python 和 Pandas(在 Jupyter Notebook 中),并按照 this tutorial,使用 pandas.DataFrame.plot 绘制我的数据框。我有一个问题,类似于教程,当我为绘图添加颜色时,x 轴不再有值或标题。
df.plot.scatter(x="Weight", y="Height")
df.plot.scatter(x="Weight", y="Height", c="Team Color")
有没有一种简单的方法可以将 x 轴标题和值保留在彩色图中?
完整代码:
import pandas as pd
# dataframe of height and weight football players
df = pd.DataFrame({
'Height': [167, 175, 170, 186, 190, 188, 158, 169, 183, 180],
'Weight': [65, 70, 72, 80, 86, 94, 50, 58, 78, 85],
'Team': ['A', 'A', 'B', 'B', 'B', 'B', 'A', 'A', 'B', 'A']
})
ax = df.plot.scatter(x="Weight", y="Height")
df['Team Color'] = df['Team'].map({'A': 'Red', 'B': 'Blue'})
ax = df.plot.scatter(x="Weight", y="Height", c="Team Color")
更新:
根据@TC Arlen 的建议,我将 Pandas 从 v1.0.5 更新到 1.3.1。我的 Python 版本是 3.8.3。此更新修复了此示例的问题,但令人惊讶的是,对于代码的变体,问题仍然存在。比如Pandas documentation的代码
df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
[6.4, 3.2, 1], [5.9, 3.0, 2]],
columns=['length', 'width', 'species'])
ax2 = df.plot.scatter(x='length',
y='width',
c='species',
colormap='viridis')
但是当我运行此代码时,我再次得到没有 x 轴值或标题:
所以我的问题仍然存在。
【问题讨论】:
-
oyur 代码的最小工作示例会很好(不是指向另一个站点的链接)
-
@raphael 问题与教程相同。代码在链接中。
-
嗯,是的,但是如果那个网站消失了,没人会知道真正的问题是什么