在条形图Matploblib中设置双轴对数 [英] Setting both axes logarithmic in bar plot matploblib

查看:68
本文介绍了在条形图Matploblib中设置双轴对数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对数据进行分箱以绘制直方图.因此,我正在使用 plt.bar()函数.我想将绘图中的两个轴都设置为对数刻度.

I have already binned data to plot a histogram. For this reason I'm using the plt.bar() function. I'd like to set both axes in the plot to a logarithmic scale.

如果我设置 plt.bar(x,y,width = 10,color ='b',log = True),这使我可以将y轴设置为log,但是我不能设置x轴的对数.我已经尝试过 plt.xscale('log'),但这无法正常工作.x轴刻度消失了,条的大小没有相等的宽度.

If I set plt.bar(x, y, width=10, color='b', log=True) which lets me set the y-axis to log but I can't set the x-axis logarithmic. I've tried plt.xscale('log') unfortunately this doesn't work right. The x-axis ticks vanish and the sizes of the bars don't have equal width.

我将不胜感激.

推荐答案

默认情况下, bar 图的条形图的宽度为0.8.因此,对于较小的x值,它们在对数刻度上显得较大.如果不是指定恒定宽度,而是使用bin边缘之间的距离并将其提供给 width 参数,则条形图将具有正确的宽度.为了使它起作用,还需要将 align 设置为"edge" .

By default, the bars of a barplot have a width of 0.8. Therefore they appear larger for smaller x values on a logarithmic scale. If instead of specifying a constant width, one uses the distance between the bin edges and supplies this to the width argument, the bars will have the correct width. One would also need to set the align to "edge" for this to work.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.logspace(0, 5, num=21)
y = (np.sin(1.e-2*(x[:-1]-20))+3)**10

fig, ax = plt.subplots()
ax.bar(x[:-1], y, width=np.diff(x), log=True,ec="k", align="edge")
ax.set_xscale("log")
plt.show()

我无法为对数缩放重现丢失的刻度标签.这可能是由于问题中未显示的代码中的某些设置,或者是由于使用了较旧的matplotlib版本.此处的示例可与matplotlib 2.0配合使用.

I cannot reproduce missing ticklabels for a logarithmic scaling. This may be due to some settings in the code that are not shown in the question or due to the fact that an older matplotlib version is used. The example here works fine with matplotlib 2.0.

这篇关于在条形图Matploblib中设置双轴对数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆