Pandas 水平排列两个图
作为练习,我用matplotlib复制了《经济学人》中的一个情节 到目前为止,我可以生成一个随机数据并独立生成两个图。我现在正努力把它们水平地放在一起Pandas 水平排列两个图,pandas,matplotlib,Pandas,Matplotlib,作为练习,我用matplotlib复制了《经济学人》中的一个情节 到目前为止,我可以生成一个随机数据并独立生成两个图。我现在正努力把它们水平地放在一起 import pandas as pd import matplotlib.pyplot as plt import numpy as np %matplotlib inline df1 = pd.DataFrame({"broadcast": np.random.randint(110, 150,size=8),
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
df1 = pd.DataFrame({"broadcast": np.random.randint(110, 150,size=8),
"cable": np.random.randint(100, 250, size=8),
"streaming" : np.random.randint(10, 50, size=8)},
index=pd.Series(np.arange(2009,2017),name='year'))
df1.plot.bar(stacked=True)
df2 = pd.DataFrame({'usage': np.sort(np.random.randint(1,50,size=7)),
'avg_hour': np.sort(np.random.randint(0,3, size=7) + np.random.ranf(size=7))},
index=pd.Series(np.arange(2009,2016),name='year'))
plt.figure()
fig, ax1 = plt.subplots()
ax1.plot(df2['avg_hour'])
ax2 = ax1.twinx()
ax2.bar(left=range(2009,2016),height=df2['usage'])
plt.show()
你应该尝试使用子图。首先,通过
plt.figure()
创建一个地物。然后添加一个子图(121),其中1是行数,2是列数,最后1是第一个图。然后绘制第一个数据帧,请注意,应使用创建的轴ax1。然后添加第二个子批(122),并对第二个数据帧重复。我将轴ax2
更改为ax3
,因为现在一个图形上有三个轴。下面的代码生成了我相信您正在寻找的。然后可以分别处理每个情节的美学效果
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
df1 = pd.DataFrame({"broadcast": np.random.randint(110, 150,size=8),
"cable": np.random.randint(100, 250, size=8),
"streaming" : np.random.randint(10, 50, size=8)},
index=pd.Series(np.arange(2009,2017),name='year'))
ax1 = fig.add_subplot(121)
df1.plot.bar(stacked=True,ax=ax1)
df2 = pd.DataFrame({'usage': np.sort(np.random.randint(1,50,size=7)),
'avg_hour': np.sort(np.random.randint(0,3, size=7) + np.random.ranf(size=7))},
index=pd.Series(np.arange(2009,2016),name='year'))
ax2 = fig.add_subplot(122)
ax2.plot(df2['avg_hour'])
ax3 = ax2.twinx()
ax3.bar(left=range(2009,2016),height=df2['usage'])
plt.show()
您应该尝试使用子批。首先,通过
plt.figure()
创建一个地物。然后添加一个子图(121),其中1是行数,2是列数,最后1是第一个图。然后绘制第一个数据帧,请注意,应使用创建的轴ax1。然后添加第二个子批(122),并对第二个数据帧重复。我将轴ax2
更改为ax3
,因为现在一个图形上有三个轴。下面的代码生成了我相信您正在寻找的。然后可以分别处理每个情节的美学效果
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
df1 = pd.DataFrame({"broadcast": np.random.randint(110, 150,size=8),
"cable": np.random.randint(100, 250, size=8),
"streaming" : np.random.randint(10, 50, size=8)},
index=pd.Series(np.arange(2009,2017),name='year'))
ax1 = fig.add_subplot(121)
df1.plot.bar(stacked=True,ax=ax1)
df2 = pd.DataFrame({'usage': np.sort(np.random.randint(1,50,size=7)),
'avg_hour': np.sort(np.random.randint(0,3, size=7) + np.random.ranf(size=7))},
index=pd.Series(np.arange(2009,2016),name='year'))
ax2 = fig.add_subplot(122)
ax2.plot(df2['avg_hour'])
ax3 = ax2.twinx()
ax3.bar(left=range(2009,2016),height=df2['usage'])
plt.show()
对此的更新应为
ax3.bar(范围(20092016),高度=df2['usage'])
对此的更新应为ax3.bar(范围(20092016),高度=df2['usage'])