mon*_*ty0 3 python plot matplotlib
使用上一个问题中的相同代码,此示例生成以下图表:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
data = (0, 1890,865, 236, 6, 1, 2, 0 , 0, 0, 0 ,0 ,0 ,0, 0, 0)
ind = range(len(data))
width = 0.9 # the width of the bars: can also be len(x) sequence
p1 = plt.bar(ind, data, width)
plt.xlabel('Duration 2^x')
plt.ylabel('Count')
plt.title('DBFSwrite')
plt.axis([0, len(data), -1, max(data)])
ax = plt.gca()
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
plt.savefig('myfig')
Run Code Online (Sandbox Code Playgroud)
而不是刻度标签为0,2,4,6,8 ...我宁愿让它们在每个标记处标记,并继续使用2 ^ x的值:1,2,4,8,16等. 我怎样才能做到这一点?然后更好的是,我可以将标签置于条形下方而不是左边缘吗?
xticks()
是你想要的:
# return locs, labels where locs is an array of tick locations and
# labels is an array of tick labels.
locs, labels = xticks()
# set the locations of the xticks
xticks( arange(6) )
# set the locations and labels of the xticks
xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )
Run Code Online (Sandbox Code Playgroud)
因此,要使得在1..4中的x为2 ^ x的刻度,请执行以下操作:
tick_values = [2**x for x in arange(1,5)]
xticks(tick_values,[("%.0f" % x) for x in tick_values])
Run Code Online (Sandbox Code Playgroud)
要使标签居中而不是栏的左侧,请使用align='center'
何时调用bar
.
这是结果:
实现这一目标的一种方法是利用a Locator
和a Formatter
.这使得可以交互地使用绘图而不会"丢失"刻度线.在这种情况下,我建议MultipleLocator
并FuncFormatter
在下面的示例中看到.
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FuncFormatter
data = (0, 1890,865, 236, 6, 1, 2, 0 , 0, 0, 0 ,0 ,0 ,0, 0, 0)
ind = range(len(data))
width = 0.9 # the width of the bars: can also be len(x) sequence
# Add `aling='center'` to center bars on ticks
p1 = plt.bar(ind, data, width, align='center')
plt.xlabel('Duration 2^x')
plt.ylabel('Count')
plt.title('DBFSwrite')
plt.axis([0, len(data), -1, max(data)])
ax = plt.gca()
# Place tickmarks at every multiple of 1, i.e. at any integer
ax.xaxis.set_major_locator(MultipleLocator(1))
# Format the ticklabel to be 2 raised to the power of `x`
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: int(2**x)))
# Make the axis labels rotated for easier reading
plt.gcf().autofmt_xdate()
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
plt.savefig('myfig')
Run Code Online (Sandbox Code Playgroud)