首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Matplotlib -为每个bin添加标签

Matplotlib -为每个bin添加标签
EN

Stack Overflow用户
提问于 2011-06-15 11:34:06
回答 3查看 116K关注 0票数 79

我目前正在使用Matplotlib创建一个直方图:

代码语言:javascript
复制
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
...
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1,)
n, bins, patches = ax.hist(measurements, bins=50, range=(graph_minimum, graph_maximum), histtype='bar')

#ax.set_xticklabels([n], rotation='vertical')

for patch in patches:
    patch.set_facecolor('r')

pyplot.title('Spam and Ham')
pyplot.xlabel('Time (in seconds)')
pyplot.ylabel('Bits of Ham')
pyplot.savefig(output_filename)

我想让x轴标签更有意义一些。

首先,这里的x轴刻度似乎被限制为五个刻度。无论我做什么,我似乎不能改变这一点-即使我添加更多的xticklabels,它也只使用前五个。我不确定Matplotlib是如何计算的,但我假设它是从范围/数据自动计算出来的?

有没有什么方法可以提高x-tick标签的分辨率--甚至可以提高到每个条形/条形的分辨率?

(理想情况下,我还希望将秒重新格式化为微秒/毫秒,但这是另一个问题)。

其次,我想要每个标记为的条形图--带有该条形图中的实际数量,以及占所有条形图总数的百分比。

最终输出可能如下所示:

这样的事情在Matplotlib中是可能的吗?

干杯,维克多

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-06-15 12:35:49

好的!去设定时间,只是,嗯.设置刻度(请参见matplotlib.pyplot.xticksax.set_xticks)。(此外,您也不需要手动设置补丁的面部颜色。您可以只传递一个关键字参数。)

对于其余部分,您需要对标签做一些稍微花哨的事情,但是matplotlib使它变得相当简单。

举个例子:

代码语言:javascript
复制
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

data = np.random.randn(82)
fig, ax = plt.subplots()
counts, bins, patches = ax.hist(data, facecolor='yellow', edgecolor='gray')

# Set the ticks to be at the edges of the bins.
ax.set_xticks(bins)
# Set the xaxis's tick labels to be formatted with 1 decimal place...
ax.xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))

# Change the colors of bars at the edges...
twentyfifth, seventyfifth = np.percentile(data, [25, 75])
for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]):
    if rightside < twentyfifth:
        patch.set_facecolor('green')
    elif leftside > seventyfifth:
        patch.set_facecolor('red')

# Label the raw counts and the percentages below the x-axis...
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
for count, x in zip(counts, bin_centers):
    # Label the raw counts
    ax.annotate(str(count), xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -18), textcoords='offset points', va='top', ha='center')

    # Label the percentages
    percent = '%0.0f%%' % (100 * float(count) / counts.sum())
    ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -32), textcoords='offset points', va='top', ha='center')


# Give ourselves some more room at the bottom of the plot
plt.subplots_adjust(bottom=0.15)
plt.show()

票数 128
EN

Stack Overflow用户

发布于 2017-07-16 08:46:29

若要将SI前缀添加到轴标签,请使用QuantiPhy。事实上,在它的文档中有一个例子展示了如何做这件事:MatPlotLib Example

我认为你会在你的代码中添加类似这样的东西:

代码语言:javascript
复制
from matplotlib.ticker import FuncFormatter
from quantiphy import Quantity

time_fmtr = FuncFormatter(lambda v, p: Quantity(v, 's').render(prec=2))
ax.xaxis.set_major_formatter(time_fmtr)
票数 0
EN

Stack Overflow用户

发布于 2020-07-27 10:02:23

我想要添加到直方图中"density = True“的曲线图中的一件事是每个bin搜索的相对频率值,但我找不到一个可以做到这一点的函数。我制作的解决方案如下图所示:

函数:

代码语言:javascript
复制
def label_densityHist(ax, n, bins, x=4, y=0.01, r=2, **kwargs):
"""
Add labels,relative value of bin, to each bin in a density histogram .
:param ax: Object axe of matplotlib
        The axis to plot.
:param n: list, array of int, float
        The values of the histogram bins.
:param bins: list, array of int, float
        The edges of the bins.
:param x: int, float
        Related the x position of the bin labels. The higher, the lower the value on the x-axis.
        Default: 4
:param y: int, float
        Related the y position of the bin labels. The higher, the greater the value on the y-axis.
        Default: 0.01
:param r: int
        Number of decimal places.
        Default: 2
:param **kwargs: Text properties in matplotlib
:return: None


Example

import matplotlib.pyplot as plt
import numpy as np

dados = np.random.randn(100)

axe = plt.gca()
n, bins, _ = axe.hist(x=dados, edgecolor='black')
label_densityHist(axe,n, bins)
plt.show()

Example:
import matplotlib.pyplot as plt
import numpy as np


dados = np.random.randn(100)

axe = plt.gca()
n, bins, _ = axe.hist(x=dados, edgecolor='black')
label_densityHist(axe,n, bins, x=6, fontsize='large')
plt.show()


Reference:
[1]https://matplotlib.org/3.1.1/api/text_api.html#matplotlib.text.Text

"""

k = []
# calculate the relative frequency of each bin
for i in range(0,len(n)):
    k.append((bins[i+1]-bins[i])*n[i])

# rounded
k = around(k,r); #print(k)

# plot the label/text to each bin
for i in range(0, len(n)):
    x_pos = (bins[i + 1] - bins[i]) / x + bins[i]
    y_pos = n[i] + (n[i] * y)
    label = str(k[i]) # relative frequency of each bin
    ax.text(x_pos, y_pos, label, kwargs)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6352740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档