首页 > 解决方案 > how to plot a dataframe with two different axes in pandas matplotlib

问题描述

So my data frame is like this:

             6month  final-formula  numPatients6month
160243.0       1       0.401193                417
172110.0       2       0.458548                323
157638.0       3       0.369403                268
180306.0       4       0.338761                238
175324.0       5       0.247011                237
170709.0       6       0.328555                218
195762.0       7       0.232895                190
172571.0       8       0.319588                194
172055.0       9       0.415517                145
174609.0      10       0.344697                132
174089.0      11       0.402965                106
196130.0      12       0.375000                 80

and I am plotting 6month, final-formula column

  dffinal.plot(kind='bar',x='6month', y='final-formula')
import matplotlib.pyplot as plt
plt.show()

till now its ok, it shows 6month in the x axis and final-formula in the y-axis. what I want is that to show the numPatients6month in the same plot, but in another y axis. according to the below diagram. I want to show numPatients6month in the position 1, or simply show that number on above each bar.

enter image description here

I tried to conduct that by twinx, but it seems it is for the case we have two plot and we want to plot it in the same figure.

fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
ax.set_ylabel('numPatients6month')

I appreciate your help :)

标签: pandasmatplotlibgroup-bydata-visualizationdata-analysis

解决方案


这是解决它的解决方案。我在这里分享可能会帮助某人:)

ax=dffinal.plot(kind='bar',x='6month', y='final-formula')
import matplotlib.pyplot as plt
ax2 = ax.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
dffinal.plot(ax=ax2,x='6month', y='numPatients6month')
plt.show()

推荐阅读