【问题标题】:Pandas DF scatter-plot: adding color removes x-axisPandas DF 散点图:添加颜色会删除 x 轴
【发布时间】: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 问题与教程相同。代码在链接中。
  • 嗯,是的,但是如果那个网站消失了,没人会知道真正的问题是什么

标签: python pandas plot


【解决方案1】:

你可以这样做:

ax = df.plot.scatter(x="Weight", y="Height", c="Team Color")
ax.set_xlabel('Weight')

编辑:熊猫散点图功能看起来有些奇怪,不同的版本会产生不同的问题。因此,坚持使用纯 pyplot 将为 iris 数据集示例提供以下内容:

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'])

plt.scatter(x=df['length'], y=df['width'], c=df['species'], cmap='viridis')
cbar = plt.colorbar()
cbar.set_label('Species')
ax = plt.gca()
ax.set_xlabel('length')
ax.set_ylabel('width')

【讨论】:

  • 这似乎并没有改变情节。
  • 拍摄,这适用于我的系统。也许尝试更新你的熊猫版本?我的是版本1.3.1。你的是什么?
  • 我的版本是 1.0.5。更新到 1.3.1 后,即使没有添加您的建议,问题也已解决。谢谢!
  • 奇怪的是问题仍然存在......我编辑了帖子。
  • @RdBasha Weird,但我得到了和你一样的东西。我编辑了我的帖子以包含纯 pyplot 实现的正确图。这对你有用吗?
猜你喜欢
  • 2018-06-19
  • 2019-05-14
  • 1970-01-01
  • 2015-05-28
  • 1970-01-01
  • 2017-08-23
  • 2020-10-10
  • 1970-01-01
  • 2020-02-15
相关资源
最近更新 更多