我有一个包含 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()
最佳答案
因为您有 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()
有更多的列,你当然可以遍历它们
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/