python - 从 Pandas DataFrame 绘图时控制颜色、图例,每个 x 有多个 y 值

标签 python pandas matplotlib

我有一个包含 3 列的数据框。我想在 x 轴上绘制 col1,在 y 轴上绘制 col2 和 col3。 Col1 具有重复值,因此对于每个 x 值,都有重复的 y 值。

示例数据框:

DF = pd.DataFrame({"name": ["Alice", "Alice", "Charles", "Charles", "Kumar", "Kumar"],
              "height": [124, 126, 169, 170, 175, 174],
              "weight": [100, 105, 123, 125, 139, 140]})

DF 

    name    height  weight
  0 Alice   124     100
  1 Alice   126     105
  2 Charles 169     123
  3 Charles 170     125
  4 Kumar   175     139
  5 Kumar   174     140

我要:

A) 每个人在 x 轴上只出现一次

B) 保持所有高度为一种颜色,所有重量为另一种颜色,并使用准确、不重复的图例

到目前为止,我只能得到 A 或 B,不能同时得到。以下是我正在尝试的内容和输出。对于 A,这很有帮助 ( Python Scatter Plot with Multiple Y values for each X )

对于 A:

f = DF.groupby("name", as_index=False).agg({"height":lambda x: tuple(x), "weight":lambda x: tuple(x)})
for x, (y1, y2) in enumerate(zip(f.height.values.tolist(), f.weight.values.tolist()), start=1):

    plt.scatter([x] * len(y1), y1, color='green', marker='o', label="height")
    plt.scatter([x] * len(y2), y2, color='blue', marker='o', label="weight")

plt.xticks(np.arange(1, len(f.name.values) +1))
plt.axes().set_xticklabels(f.name.values.tolist())
plt.legend(loc="best")
plt.show()

对于乙:

ax = DF.plot(style="o", figsize=(7, 5), xlim=(-1, 6))
ax.set_xticks(DF.index)
ax.set_xticklabels(DF.name, rotation=90)
plt.show()

enter image description here

enter image description here

最佳答案

因为您有 2 列,所以您可以绘制 2 个散点图,每个散点图都有自己的标签。

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({"name": ["Alice", "Alice", "Charles", "Charles", "Kumar", "Kumar"],
              "height": [124, 126, 169, 170, 175, 174],
              "weight": [100, 105, 123, 125, 139, 140]})

plt.scatter(df.name, df.height, label="height")
plt.scatter(df.name, df.weight, label="weight")
plt.legend()
plt.show()

enter image description here

有更多的列,你当然可以遍历它们

for col in ["height", "weight"]:
    plt.scatter(df.name, df[col], label=col)

关于python - 从 Pandas DataFrame 绘图时控制颜色、图例,每个 x 有多个 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50263712/

相关文章:

python - 如何在 matplotlib 中很好地绘制剪裁的分层艺术家?

python - django 反序列化尝试将输入编码为 ascii?

python - 检查字符串是否是名称的可能缩写

python - Microsoft BotFramework Python 机器人部署

python - 为什么在使用 scatter() 时会出现 AttributeError 而在使用 plot() 时却不会

3d - 使用 LaTeX 标签时 Matplotlib mplot3d 标签和刻度重叠

python - 如何用正则表达式编写递归scrapy规则?

python - 使用多个时间戳对多个用户数据进行分组

python - 如何删除 .0 而不弄乱数字 10

python - 构建特定 dtype 的数据框时,pandas 是否具有默认填充值?