[英]How do I get the locations of the x-ticks on a bar plot created in pandas?
我有一個從熊貓數據框創建的分組條形圖。 我想在每組條形圖上設置一條斧頭線,但要使其停止在條形圖組的邊緣之外,因此我需要找到一種方法來獲取xtick位置列表以及繪制的條形圖寬度,這樣我就可以將xmin和xmax args放入axhline中。 如果我不能這樣做,是否可以在繪圖功能中設置刻度位置並使用這些值?
我嘗試過的唯一一件事是手動設置線條位置,但是我繪制的圖來自具有不同列數的數據框,因此我在圖表上的組數並不總是相同。
使用get_xticks
並沒有多大幫助,因為它只給了我一個[1,2,3]
數組,這對axhline沒有用。
數據框的設置如下(數據框將始終具有3行,但具有可變的列數):
import matplotlib.pyplot as plt
import pandas as pd
fig, ax = plt.subplots()
df = pd.DataFrame(data=[[1,2,3], [4,5,6], [7,8,9]], index=['type1', 'type2', 'type3'], columns=['group1', 'group2', 'group3'])
df.plot(kind='bar', ax=ax)
每個組都有一個閾值,我想在圖形上用水平線表示,但是在我的某些情況下,我有10或11個組,所以我不想在整個圖上都畫線,因為這很難理解。
提前致謝
條形圖從其中心位置伸出width
的+/-一半。 因此,位置1
處的棒組的寬度為1-0.6/2 = 0.7
到1+0.6/2=1.3
寬度為0.6
。
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
fig, ax = plt.subplots()
df = pd.DataFrame(data=[[1,2,3], [4,5,6], [7,8,9]],
index=['type1', 'type2', 'type3'],
columns=['group1', 'group2', 'group3'])
width = 0.6
ax = df.plot(kind='bar', ax=ax, width=width)
mean= df.mean(axis=1)
x = np.arange(len(df.columns))
ax.hlines(mean, x - width/2, x + width/2)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.