Python 带有matplotlib的双图:属性错误
我有这样一个熊猫数据框:Python 带有matplotlib的双图:属性错误,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有这样一个熊猫数据框: nan 0 ingredient contribution count 0 0.0 cracker 0.088844873 11 1 2.0 water 0.044386494 125 2 3.0 oil 0.034567456 10 3 4.0 flour 0.030855063 186 ... 我想创建一个类似这样的双
nan 0 ingredient contribution count
0 0.0 cracker 0.088844873 11
1 2.0 water 0.044386494 125
2 3.0 oil 0.034567456 10
3 4.0 flour 0.030855063 186
...
我想创建一个类似这样的双图形:
我尝试的代码:
import matplotlib.pyplot as plt #importing libraries
import numpy as np
plt.figure(1) #creating empty figure
t = np.arange(0.0, 2.0, 0.01)
fig_contr = df[['ingredient','contribution']] #selecting columns
fig_count = df[['ingredient','count']]
plt.subplot(211) #creating subplot
plt.plot(t, fig_contr) #plotting subplot
plt.subplot(212)
plt.plot(t, fig_count)
但我得到了这个错误:AttributeError:'DataFrame'对象没有属性'find'
我应该如何创建我想要获得的图形 一种可能的解决方案是使用: 还可以更改x轴标签的方向:
plt.figure(1) #creating empty figure
df.set_index('ingredient', inplace=True)
fig_contr = df['contribution'] #selecting columns
fig_count = df['count']
plt.subplot(211) #creating subplot
fig_contr.plot.bar(rot=0) #plotting subplot
plt.subplot(212)
fig_count.plot.bar(rot=0)
plt.show()
谢谢你,耶斯雷尔!不幸的是,我收到了错误消息:TypeError:Empty'DataFrame':没有要打印的数字数据。你知道如何摆脱它吗?什么是
打印df.dtypes
?dtype是一个对象。你的情况是整数/浮点数吗?我不明白了。。现在我得到了另一个错误:KeyError:“component”是的,您需要转换为数字-最简单的方法是使用astype
-df['contribution']=df['contribution'].astype(float)df['count']=df['count'].astype(int)
。
plt.figure(1) #creating empty figure
df.set_index('ingredient', inplace=True)
fig_contr = df['contribution'] #selecting columns
fig_count = df['count']
plt.subplot(211) #creating subplot
fig_contr.plot.bar(rot=0) #plotting subplot
plt.subplot(212)
fig_count.plot.bar(rot=0)
plt.show()