[英]How to change scatter XY plot color dependent from string Z value?
I would like that make scatter plot with different dots colors, dependent from column 'Value'
.我希望使用不同的点颜色制作散点图,取决于列'Value'
。 For example all "rand"
dots would be blue and "qmax"
red.例如,所有"rand"
点都是蓝色的,而"qmax"
点是红色的。 Here is my code:这是我的代码:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'State': [1000, 1002, 1001, 1003, 1000, 1003, 1001],
'Score': [62, 47, 55, 74, 31, 50, 60],
'Value': ['rand','qmax','rand','qmax','rand','qmax','qmax']
}, columns=['State', 'Score', 'Value'])
# Create figure with plot
fig, ax1 = plt.subplots()
ax1.scatter(df['State'], df['Score'])
plt.show()
My dataframe:我的数据框:
State Score Value
0 1000 62 rand
1 1002 47 qmax
2 1001 55 rand
3 1003 74 qmax
4 1000 31 rand
5 1003 50 qmax
6 1001 60 qmax
You could iterate the values in the 'Value'
column and, in each iteration, filter the dataframe and plot the filtered data:您可以迭代'Value'
列中的值,并在每次迭代中过滤数据框并绘制过滤后的数据:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'State': [1000, 1002, 1001, 1003, 1000, 1003, 1001],
'Score': [62, 47, 55, 74, 31, 50, 60],
'Value': ['rand','qmax','rand','qmax','rand','qmax','qmax']
}, columns=['State', 'Score', 'Value'])
print(df)
# Create figure with plot
fig, ax1 = plt.subplots()
for value in df['Value'].unique():
ax1.scatter(df[df['Value'] == value]['State'], df[df['Value'] == value]['Score'])
plt.show()
If you want to choose the color for each individual value in 'Value'
, you can define a dictionary as this one:如果要为'Value'
每个单独值选择颜色,您可以将字典定义为:
colors = {'rand': 'blue', 'qmax': 'red'}
And specify the color
parameter in the scatter
call:并在scatter
调用中指定color
参数:
for value in df['Value'].unique():
ax1.scatter(df[df['Value'] == value]['State'], df[df['Value'] == value]['Score'], color = colors[value])
You could also show a legend:您还可以显示图例:
for value in df['Value'].unique():
ax1.scatter(df[df['Value'] == value]['State'], df[df['Value'] == value]['Score'], color = colors[value], label = value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.