使用matplotlib绘图时如何手动设置字符串颜色?
例如,我有以下数据集。
# Generate data...
import pandas as pd
seed(1)
df = pd.DataFrame({
'x':np.random.random(10),
'y':np.random.random(10),
'z':np.random.choice(['yes','no'], 10)
})
df
x y z
0 0.417022 0.419195 no
1 0.720324 0.685220 no
2 0.000114 0.204452 no
3 0.302333 0.878117 no
4 0.146756 0.027388 no
5 0.092339 0.670468 no
6 0.186260 0.417305 yes
7 0.345561 0.558690 no
8 0.396767 0.140387 no
9 0.538817 0.198101 yes
我想使用以下代码将"is"绘制为“红色”,将“否”绘制为“蓝色”,但如何设置颜色?
# Plot...
plt.scatter(df.x, df.y, c= df.z)
请您参考如下方法:
我认为这条线会做你想做的事:
plt.scatter(df.x, df.y, c=['red' if x == 'yes' else 'blue' for x in df.z])
