字典到 plot.bar 有两个值,一个在 y 轴上,另一个在 x 轴上,带有 dict.key

时间:2021-07-09 08:09:52

标签: pandas dataframe matplotlib plot

字典到plot.bar,带有两个数据集和一个dict.keys显示x-axis,带有A,B,C,D,E,F,I,J,K,L,M,N映射使用排序值 1,2,3,4,5,6,7,8,9,10,11,12 ,示例数据排序像这样 N 1, B 2", C 3, D 4, E 5, {{1} }、I 6F 7J 8K 9L 10M 11预期条形图

数据集

A 12

预期条形图 Expected bar chart

尝试过的 Python 代码:(有错误)

x = {'A': ['12', '100'],
     'B': ['2', '101'],
     'C': ['3', '102'],
     'D': ['4', '103'],
     'E': ['5', '104'],
     'F': ['7', '105'],
     'I': ['6', '106'],
     'J': ['8', '107'],
     'K': ['9', '108'],
     'L': ['10', '109'],
     'M': ['11', '110'],
     'N': ['1', '111']}

2 个答案:

答案 0 :(得分:1)

这就是错误所说的数据是字符串,因此通过 astype() 方法将其类型转换为 int/float:

df=pd.DataFrame(x)
df=df.T.astype(int)
#If nan's are present in your dataset then typecast it to float
#df=df.T.astype(float)
#Since you only need to plot the second record so:
df[1].plot(kind='bar',title="first record in bar second record in x-axis")

enter image description here

如果你想要这样:

df=pd.DataFrame(x)
df=df.T.astype(int)
df=df.set_index(0,append=True)
df=df.sort_index(level=1)
df.plot(kind='bar',title="first record in bar second record in x-axis",rot=20)
plt.legend(['second record'])

enter image description here

答案 1 :(得分:0)

如果您不需要股票代码中的排序值,则可以使用以下方法:

x = {'A': ['12', '100'],
     'B': ['2', '101'],
     'C': ['3', '102'],
     'D': ['4', '103'],
     'E': ['5', '104'],
     'F': ['7', '105'],
     'I': ['6', '106'],
     'J': ['8', '107'],
     'K': ['9', '108'],
     'L': ['10', '109'],
     'M': ['11', '110'],
     'N': ['1', '111']}
dataFrame = pd.DataFrame(x).T
dataFrame.columns = ['level', 'value']
dataFrame = dataFrame.astype('int')
dataFrame.sort_values('level', inplace=True)
dataFrame['value'].plot.bar(title="first record in bar second record in x-axis")