热门使用matplotlib在条形图上添加范围虚线框?

时间:2016-04-05 08:29:25

标签: python matplotlib bar-chart

我使用Birt制作了条形图,但由于技术的改变,我现在必须使用Matplotlib。我想知道是否有可能(以及如何)使用Matplotlib制作类似的图表,尤其是围绕前80%的条形的范围虚线方式,例如:

birt chart

我没有找到任何关于如何制作它的文档。

有人知道如何继续吗?

1 个答案:

答案 0 :(得分:2)

像这样的东西。

您可以使用matplotlib.patches.Rectangle作为虚线框。

我还将spines向外移动以匹配您的情节风格(代码取自this example

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
import matplotlib.ticker as ticker

# Fake some data
x = np.array([15,25,35,45,45,45,45,45,75,75,95,150,160,170,170,1040])
y = np.arange(0.1,16.1,1)
percent = np.array([(100.*float(i)/x.sum()) for i in x])

# Create Figure and Axes
fig,ax = plt.subplots(1)

# Plot the bars
ax.barh(y,x)

# Move left and bottom spines outward by 5 points
ax.spines['left'].set_position(('outward', 5))
ax.spines['bottom'].set_position(('outward', 5))
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')

# Set the axes limits and tick locations
ax.set_ylim(0,16)
ax.set_yticklabels([])
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

ax.set_xlim(0,1100)
ax.xaxis.set_major_locator(ticker.MultipleLocator(100))

# Add the rectangle
rect = Rectangle( (0,10), 1100, 6, linestyle = 'dashed', facecolor = 'None', clip_on=False)
ax.add_patch(rect)

# Add the percentage labels
for p,xi,yi in zip(percent,x,y):
    ax.text(xi+5,yi+0.2,'{:2.0f}\%'.format(p))

plt.show()

enter image description here