color = []
for key,value in ms.iterrows():
if(value['Color']=='Blue'):
color.append('b')
elif(value['Color']=='Green'):
color.append('g')
elif(value['Color']=='Red'):
color.append('r')
elif(value['Color']=='Yellow'):
color.append('y')
elif(value['Color']=='Orange'):
color.append('o')
else:
color.append('k')
ax =ms[['Height','Color']].plot(x='Color', kind='bar', title="Correlation",
figsize=(15,10), color=color legend=True, fontsize=12)
ax.set_xlabel("Colors", fontsize=12)
ax.set_ylabel("Height", fontsize=12)
我的意图是绘制一个条形图,显示颜色与高度。我设法做到了。然而,我希望每个条显示各自的颜色。根据数据集,我希望第一条显示红色...等等。我尝试添加颜色,但它仍然显示只有一种颜色。
诀窍是创建多列数据帧并使用stacked=True
选项。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({"Height" : [5,3,6,4],
"Color" : ["Blue", "Green", "Red", "Yellow"]})
color = []
for key,value in df.iterrows():
if(value['Color']=='Blue'):
color.append('b')
elif(value['Color']=='Green'):
color.append('g')
elif(value['Color']=='Red'):
color.append('r')
elif(value['Color']=='Yellow'):
color.append('y')
elif(value['Color']=='Orange'):
color.append('o')
else:
color.append('k')
df2 = pd.DataFrame(np.diag(df["Height"]), columns=df["Color"], index=df["Color"])
ax = df2.plot(kind='bar', title="Correlation", color=color, legend=True,
fontsize=12, stacked=True)
ax.set_xlabel("Colors", fontsize=12)
ax.set_ylabel("Height", fontsize=12)
plt.show()
您不需要创建if/res条件:
import pandas as pd
df = pd.DataFrame({"Height" : [5,3,6,4],
"Color" : ["Blue", "Green", "Red", "Yellow"]})
df.set_index('Color').Height.plot(kind='bar',color=df.Color)