本文介绍了matplotlib一起绘制条形图和折线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个图表中将条形图和线形图绘制在一起.当我绘制条形图时,它可以正确显示(g1和g10显示完成):

I want to plot bar and line together in one chart. When I plot bars, it displays correctly(g1 and g10 are displayed completed):

但是,如果我在绘图中添加一条线:

However, if I add a line to the plot:

m1_t[['abnormal','fix','normal']].plot(kind='bar')
m1_t['bad_rate'].plot(secondary_y=True)

条形图不完整,如下所示(g1和g10被切碎):

The bar chart is incomplete as below(g1 and g10 are chopped):

您知道如何解决此问题吗?

Any idea how to fix this problem?

推荐答案

您必须使用xlim扩展x轴:

You have to expand x axis with xlim:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

width = .35 # width of a bar

m1_t = pd.DataFrame({
 'abnormal' : [90,40,30,30,30,25,25,20,15,10],
 'fix' : [60,70,65,70,70,60,50,45,45,45],
 'normal' : [140,160,170,180,190,200,210,220,230,240],
 'bad_rate' : [210,100,100,70,70,75,70,60,65,60]})

m1_t[['abnormal','fix','normal']].plot(kind='bar', width = width)
m1_t['bad_rate'].plot(secondary_y=True)

ax = plt.gca()
plt.xlim([-width, len(m1_t['normal'])-width])
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5', 'G6', 'G7', 'G8', 'G9', 'G10'))

plt.show()

对于以后的问题,请发布您的数据框.

For future question post your dataframe.

这篇关于matplotlib一起绘制条形图和折线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 15:17