python pandas用一张图同时显示柱形图和折线图,但是折线图不显示

pandas用一张图同时显示柱形图和折线图,但是折线图不显示
fig = plt.figure() # Create matplotlib figure

ax = fig.add_subplot() # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.

data6.plot(kind='bar',x='year',y=['0-14','15-64','65-'],stacked=True,ax=ax)
data6.plot(kind='line',x='year',y='aging rate',ax=ax2)

ax.set_ylabel('amount')
ax2.set_ylabel('rate')

plt.show()

img

望采纳。有2种方式修改代码都可以达到你的目的:

  • ① 共用一个ax,那么代码这样改
# Create matplotlib figure
fig = plt.figure()

# Create matplotlib axes
ax = fig.add_subplot()

# Create bar plot on ax
data6.plot(kind='bar', x='year', y=['0-14','15-64','65-'], stacked=True, ax=ax)

# Create line plot on ax
data6.plot(kind='line', x='year', y='aging rate', ax=ax)

# Set y-labels
ax.set_ylabel('amount')
ax.right_ax.set_ylabel('rate')

# Show plot
plt.show()
  • ② 显示ax2,那么代码这样改
# Create matplotlib figure
fig = plt.figure()

# Create matplotlib axes
ax = fig.add_subplot()

# Create another axes that shares the same x-axis as ax
ax2 = ax.twinx()

# Create bar plot on ax
data6.plot(kind='bar', x='year', y=['0-14','15-64','65-'], stacked=True, ax=ax)

# Create line plot on ax2
data6.plot(kind='line', x='year', y='aging rate', ax=ax2)

# Set y-labels
ax.set_ylabel('amount')
ax2.set_ylabel('rate')

# Show plot
plt.show()