Python的颜色呈散点排列

2024-10-02 16:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想散点图2个变量和颜色点根据第三个变量,这是一个定性变量包含2类

df.plot(kind='scatter', x='TotalIncome', y='LoanAmount', figsize=(10, 6))
plt.xlabel('total income')
plt.ylabel('loan amount')
plt.show()

Tags: dfplot颜色plttotal定性kindloan
1条回答
网友
1楼 · 发布于 2024-10-02 16:30:58

就第三个变量给各个点上色是很简单的。你只需要把这个定性变量映射到可以表示颜色的东西上。例如,如果第三个变量在以下代码中是“c”:

import matplotlib.pyplot as plt

def map_col(col):

    if col == 'y_odd':
        mapped_col = 0
    elif col == 'y_even':
        mapped_col = 1

    return mapped_col


x = [1, 4, 2, 7, 4, 9]
y = [4, 1, 3, 6, 8, 2]
c = ['y_even', 'y_odd', 'y_odd', 'y_even', 'y_even', 'y_even']

color = [map_col(col) for col in c]

plt.scatter(x, y, s=100, c=color, cmap="gnuplot")

plt.show()

有关可用颜色贴图的列表,请参见:

https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html

相关问题 更多 >