为不同的虚拟值更改散点图中点的颜色
Changing the color of points in scatter plot for different dummy values
在我的数据集中,我有一个 Price
列表示房价,还有 5 个虚拟列表示城市中的不同位置。我想要做的是在散点图上用不同的颜色显示数据点。
例如,在包含所有房屋价格的散点图上,我想要:
- 当
dummy1
表示房子在 Area1
等于 1 时,所有价格点都是红色。
- 当
dummy2
表示房子在 Area2
等于 2 时,所有价格点都是蓝色。
依此类推,直到最后一列。我怎样才能创建那个情节?我可以使用 plt.scatter()
创建没有颜色的散点图,但不知道如何添加颜色代码。
查看 matplotlib.pyplot.scatter
的文档,其中描述了一个参数 c
,它可以是
A sequence of color specifications of length n.
这是一个示例,它创建了 100 个随机 x
和 y
数据点。如果 y
值超过 5
,该点将为蓝色,否则为红色,如 c
列表中指定。
import matplotlib.pyplot as plt
import random
x = list(range(100))
y = [random.randint(0, 10) for _ in range(len(x))]
c = ["b" if y > 5 else "r" for y in y]
plt.scatter(x, y, c=c)
plt.show()
输出将如下所示:
在我的数据集中,我有一个 Price
列表示房价,还有 5 个虚拟列表示城市中的不同位置。我想要做的是在散点图上用不同的颜色显示数据点。
例如,在包含所有房屋价格的散点图上,我想要:
- 当
dummy1
表示房子在Area1
等于 1 时,所有价格点都是红色。 - 当
dummy2
表示房子在Area2
等于 2 时,所有价格点都是蓝色。
依此类推,直到最后一列。我怎样才能创建那个情节?我可以使用 plt.scatter()
创建没有颜色的散点图,但不知道如何添加颜色代码。
查看 matplotlib.pyplot.scatter
的文档,其中描述了一个参数 c
,它可以是
A sequence of color specifications of length n.
这是一个示例,它创建了 100 个随机 x
和 y
数据点。如果 y
值超过 5
,该点将为蓝色,否则为红色,如 c
列表中指定。
import matplotlib.pyplot as plt
import random
x = list(range(100))
y = [random.randint(0, 10) for _ in range(len(x))]
c = ["b" if y > 5 else "r" for y in y]
plt.scatter(x, y, c=c)
plt.show()
输出将如下所示: