简体   繁体   English

如何为直方图绘制两个级别的x轴标签?

[英]How to plot two level x-axis labels for a histogram?

Is there a way to do the same of this two x-axis labels but for a histogram plot? 有没有办法对这两个x轴标签做同样的事情,但对于直方图? How to add second x-axis at the bottom of the first one in matplotlib.? 如何在matplotlib的第一个底部添加第二个x轴。

I want to show the values in two levels, one for metric and the second for English units. 我想以两个级别显示值,一个用于公制,第二个用于英制单位。 I tried to adapt the script in the link above to a histogram script but I'm not sure how to connect the histogram function with the ax1. 我试图将上面链接中的脚本调整为直方图脚本,但我不确定如何将直方图函数与ax1连接。 handle. 处理。

"""
Demo of the histogram (hist) function with a few features.

In addition to the basic histogram, this demo shows a few optional features:

    * Setting the number of data bins
    * The ``normed`` flag, which normalizes bin heights so that the integral of
      the histogram is 1. The resulting histogram is a probability density.
    * Setting the face color of the bars
    * Setting the opacity (alpha value).

"""
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

# example data
mu = 100  # mean of distribution
sigma = 15  # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)

num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)

ax1.set_xlabel(r"Original x-axis: $X$")
new_tick_locations = np.array([.2, .5, .9])

def tick_function(X):
    V = 1/(1+X)
    return ["%.3f" % z for z in V]


# Move twinned axis ticks and label from top to bottom
ax2.xaxis.set_ticks_position("bottom")
ax2.xaxis.set_label_position("bottom")

# Offset the twin axis below the host
ax2.spines["bottom"].set_position(("axes", -0.15))

# Turn on the frame for the twin axis, but then hide all
# but the bottom spine
ax2.set_frame_on(True)
ax2.patch.set_visible(False)
for sp in ax2.spines.itervalues():
    sp.set_visible(False)
ax2.spines["bottom"].set_visible(True)

ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")




y = mlab.normpdf(bins, mu, sigma)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)



plt.show()

just replace your hist call by: 只需将你的hist调用替换为:

n, bins, patches = ax1.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)

Check the documentation for Axes to see what member functions are available 查看Axes文档以查看可用的成员函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM