ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – matplotlib中的两个条形图重叠错误的方式

2019-05-17 18:46:26  阅读:484  来源: 互联网

标签:python matplotlib bar-chart overlapping


我正在使用Python中的matplotlib创建一个条形图,我对重叠条有一点问题:

import numpy as np
import matplotlib.pyplot as plt

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))
width = 0.65

fig = plt.figure()
ax = fig.add_subplot(111)

ax.bar(ind+width, a, width, color='#b0c4de')

ax2 = ax.twinx()
ax2.bar(ind+width+0.35, b, 0.45, color='#deb0b0')

ax.set_xticks(ind+width+(width/2))
ax.set_xticklabels(a)

plt.tight_layout()

我希望蓝色条纹在前面,而不是红色条纹.到目前为止,我设法做到的唯一方法是切换ax和ax2,但是ylabels也将被反转,这是我不想要的.是不是有一种简单的方法告诉matplotlib在ax之前渲染ax2?

此外,右侧的ylabels被plt.tight_layout()切断.有没有办法在仍然使用tight_layout时避免这种情况?

解决方法:

也许有一种我不了解的更好的方式;但是,你可以交换ax和ax2,并交换相应的y-ticks的位置

ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
import numpy as np
import matplotlib.pyplot as plt

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))
width = 0.65

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(ind+width+0.35, b, 0.45, color='#deb0b0')

ax2 = ax.twinx()
ax2.bar(ind+width, a, width, color='#b0c4de')

ax.set_xticks(ind+width+(width/2))
ax.set_xticklabels(a)

ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")

plt.tight_layout()
plt.show()

顺便说一下,您可以使用align =’center’参数将条形图居中,而不是自己进行数学运算:

import numpy as np
import matplotlib.pyplot as plt

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(ind+0.25, b, 0.45, color='#deb0b0', align='center')

ax2 = ax.twinx()
ax2.bar(ind, a, 0.65, color='#b0c4de', align='center')

plt.xticks(ind, a)
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")

plt.tight_layout()
plt.show()

(结果与上面的结果基本相同.)

标签:python,matplotlib,bar-chart,overlapping
来源: https://codeday.me/bug/20190517/1123131.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有