Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Matplotlib-标记每个箱子_Python_Matplotlib_Visualization_Histogram_Graphing - Fatal编程技术网

Python Matplotlib-标记每个箱子

Python Matplotlib-标记每个箱子,python,matplotlib,visualization,histogram,graphing,Python,Matplotlib,Visualization,Histogram,Graphing,我目前正在使用Matplotlib创建直方图: 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

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

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轴刻度似乎仅限于五个刻度。无论我做什么,我似乎都无法改变这一点——即使我添加更多的Xticklabel,它也只使用前五个。我不确定Matplotlib是如何计算的,但我假设它是根据范围/数据自动计算的

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

(理想情况下,我也希望以微秒/毫秒的形式重新格式化秒数,但这是另一天的问题)

其次,我希望每个单独的条标上,注明该箱子中的实际数量,以及占所有箱子总数的百分比

最终输出可能如下所示:

Matplotlib是否可以实现类似的功能

干杯,
维克多

当然!要设置刻度,只需,嗯。。。设置刻度(请参见
matplotlib.pyplot.xticks
ax.Set\xticks
)。(此外,您不需要手动设置修补程序的facecolor。您只需传入关键字参数即可。)

对于其余的部分,您将需要对标签做一些稍微更有趣的事情,但是matplotlib使其变得相当简单

例如:

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()
导入matplotlib.pyplot作为plt
将numpy作为np导入
从matplotlib.ticker导入FormatStrFormatter
数据=np.random.randn(82)
图,ax=plt.子批次()
计数、存储箱、修补程序=ax.hist(数据,facecolor='黄色',edgecolor='灰色〕)
#将刻度设置为位于箱子的边缘。
ax.set_xticks(箱子)
#将xaxis的记号标签设置为小数点后1位的格式。。。
ax.xaxis.set\u major\u格式化程序(FormatStrFormatter(“%0.1f”))
#更改边缘条的颜色。。。
二十五、七十五=百分位数(数据[25,75])
对于补丁,拉链中的右侧和左侧(补丁,箱子[1:],箱子[:-1]):
如果右侧<二十五度:
patch.set_facecolor('绿色')
elif leftside>seventyfifth:
patch.set_facecolor('red'))
#标记原始计数和x轴下方的百分比。。。
垃圾箱中心=0.5*np.差异(垃圾箱)+垃圾箱[:-1]
对于计数,邮政编码中的x(计数,箱位中心):
#标记原始计数
ax.annotate(str(count),xy=(x,0),xycoords=('data','axes france'),
xytext=(0,-18),textcoords='offset points',va='top',ha='center')
#标注百分比
百分比='%0.0f%%'%(100*float(count)/counts.sum())
注释(百分比,xy=(x,0),xycoords=(‘数据’,‘轴分数’),
xytext=(0,-32),textcoords='offset points',va='top',ha='center')
#在情节的底部给我们更多的空间
plt子批次调整(底部=0.15)
plt.show()

向要使用的轴标签添加SI前缀。事实上,在它的文档中有一个例子说明了如何做这件事:

我想您应该在代码中添加如下内容:

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)

我想用“density=True”添加到柱状图中的一件事是每个箱子的相对频率值,但我找不到一个函数可以做到这一点。我提出的解决方案如图所示:

职能:

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)

啊哈,太好了。另一个注意事项-最初,我使用“fig=pyplot.figure(figsize=(32,24),)”和“ax=fig.add_subplot(1,1,1),”来设置图形的大小。但是,如果我为您的“fig,ax=pyplot.subplot()”交换第二留置权,它现在似乎忽略了我的figsize?知道为什么吗?@victorhooi-如果您只需将figsize指定为kwarg to
子地块
,它应该可以工作。例如,
fig,ax=plt.subplot(figsize=(32,34))
如果不是,可能是一个bug<代码>子绘图只是在
1.0
中添加的,作为一种方便的功能。金斯敦:啊哈,太好了,是的,那一行可以工作=)。你太棒了,伙计。最后还有一个我不明白的bug/小问题——注释文本正下方的xlabel文本——不知道如何抵消它。我试过“ax.xaxis.LABELPAD=30”,但它似乎忽略了这一点。@victorhooi-有几种不同的方法来设置刻度填充,但最简单的方法是
ax.tick_参数(axis='x',pad=30)
(这有点违反直觉)。希望有帮助!@乔·金斯顿:嗯,试过了,但它同时移动了x轴标签和记号。该死的。哈哈。不管怎样,我认为这值得再问一个问题,所以我把它转发到这里: