簡體   English   中英

Matplotlib - 如何從任何條形的頂部到 y 軸畫一條線?

[英]Matplotlib - How to draw a line from the top of any bar to the y - axis?

我創建了一個累積直方圖。 現在我想在該直方圖中從任何 bin 的頂部畫一條線到 y 軸,並像這樣顯示它的值:

你能告訴我怎么做嗎? 下面是我繪制直方圖的代碼:

plt.rcParams['ytick.right'] = plt.rcParams['ytick.labelright'] = True
plt.rcParams['ytick.left'] = plt.rcParams['ytick.labelleft'] = False

plt.figure(figsize=[8, 6])
plt.hist(df['days'], bins=range(0, 50, 1), color="dodgerblue", edgecolor='black'
                       ,cumulative=-1, density=True
                       ,histtype='barstacked')
plt.xlabel('Number of Days')
plt.ylabel('Density')

非常感謝!

單線:

plt.axhline(y, color='k', linestyle='dashed', linewidth=1)

使用它向直方圖中添加一條水平線。

在上面的代碼片段中,用 y 的平均值或值代替 y。

簡單地畫一條水平線會引起兩個問題:

  • 線將繪制在條形圖的頂部,從左到右。 要將它放在欄桿后面,請使用zorder=0
  • 這條線在最左邊仍然可見,因為那里沒有條形。 使用plt.autoscale(enable=True, axis='x', tight=True)將 x 軸更改為“緊密”布局解決了這個問題。

要在特定的 y 位置添加新的刻度,您可以獲取現有刻度的列表,創建一個包含新刻度的列表並將它們設置為新刻度。

要更改新添加的刻度線的顏色,首先要在列表中找到它的索引,然后使用該索引更改刻度線的顏色。

這種方法的一個問題是新的刻度可能與現有的刻度重疊。 這可以通過循環遍歷列表來解決,如果現有刻度比新刻度更接近某個 epsilon,則刪除現有刻度。 這在代碼示例中尚未實現。

或者,刻度值可以顯示在軸的左側,水平線的頂部。 當然,如果文本沒有足夠的位置,這會導致問題。

您可能希望將特殊刻度的值四舍五入到最接近的百分之幾,以防止其他刻度也顯示更多數字。

我用模擬數據創建了一個例子:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"days": np.random.normal(25, 10, 10000)})

plt.rcParams['ytick.right'] = plt.rcParams['ytick.labelright'] = True
plt.rcParams['ytick.left'] = plt.rcParams['ytick.labelleft'] = False

plt.figure(figsize=[8, 6])
bin_heights, _, _ = plt.hist(df['days'], bins=range(0, 50, 1), color="dodgerblue", edgecolor='black',
                             cumulative=-1, density=True,
                             histtype='barstacked')
plt.autoscale(enable=True, axis='both', tight=True)  # use axis='x' to only set the x axis tight
special_y = bin_heights[15]
# draw a horizontal line, use zorder=0 so it is drawn behind the bars
plt.axhline(special_y, 0, 1, color='red', linestyle='dashed', linewidth=1, zorder=0)

plt.yticks(list(plt.yticks()[0]) + [special_y])  # add a tick in y for special_y
# find the index of special_y in the new ticks (ticks are sorted automatically)
index_special_y = list(plt.yticks()[0]).index(special_y)
plt.gca().get_yticklabels()[index_special_y].set_color('red')  # change the color of the special tick
plt.xlabel('Number of Days')
plt.ylabel('Density')
plt.show()

示例圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM