Skip to main content
 首页 » 编程设计

python之直方图位于下方和侧面的折线图

2025年05月04日16kuangbin

这可能是我试图制作的一个不寻常的图表,所以我附上了一张插图。我不确定在 matplotlib 中是否可行,所以我想我会在这里询问如何做。

http://i.imgur.com/96JRIN2l.jpg

基本上我想在其侧面绘制一个直方图(使用 hist()),然后在顶部绘制一个折线图(使用 plot()) ,使两侧的 y 轴保持相同。

此外,我认为只有在直方图可以具有较低的不透明度时它才有效。不确定是否可以按图而不是按图设置不透明度。

到目前为止的代码:

import numpy as np 
import matplotlib.pyplot as plt 
import numpy as np 
 
fig = plt.figure() 
ax1 = fig.add_subplot(111) 
line = [0.2, 0.3, 0.37, 0.4, 0.6, 0.7, 0.72, 0.75, 0.77, 0.78, 0.79, 0.795]  
distribution = [0.2, 0.3, 0.3, 0.4, 0.7, 0.7, 0.7, 0.8] 
 
plt.hist(distribution, orientation='horizontal') 
plt.plot(range(len(line)), line, color='grey') 
 
plt.savefig("test.png") 

直方图不显示。

我该怎么做?

请您参考如下方法:

你只需要使用 twinx/twiny 两次来获得两个独立的轴(可能有一些方法可以不用做一个未使用的中间轴,但这会为您处理一些幕后细节):

import matplotlib.pyplot as plt 
import numpy as np 
 
line = [0.2, 0.3, 0.37, 0.4, 0.6, 0.7, 0.72, 0.75, 0.77, 0.78, 0.79, 0.795] 
distribution = [0.2, 0.3, 0.3, 0.4, 0.7, 0.7, 0.7, 0.8] 
 
fig, ax = plt.subplots(1, 1) 
 
ax2 = ax.twinx() 
ax3 = ax2.twiny() 
 
ax.plot(line) 
ax.set_xlabel('line xaxis') 
ax.set_ylabel('line yaxis') 
 
ax3.hist(distribution, orientation='horizontal', alpha=.5) 
ax3.invert_xaxis() 
ax3.set_xlabel('hist xaxis, note where 0 is') 
# note this needs to be ax2 due to subtle overlay issues.... 
ax2.set_ylabel('hist yaxis') 
plt.draw() 

您将不得不处理轴的细节(限制、标签、刻度等),但 ax 和 ax3 是独立的,您可以应用标准策略对每个人独立。