[英]How to draw multiple horizontal lines on each bar of a group bar chart in Python?
I am trying to draw multiple horizontal lines on each bar of a group bar chart, that looks like this:我正在尝试在组条形图的每个条上绘制多条水平线,如下所示:
By multiple horizontal lines on a bar, I mean lines that are drawn at different Y-axis levels.一条条上的多条水平线是指在不同 Y 轴水平上绘制的线。 For example, I would like to draw 1 horizontal line on Bar 3, Bar 4, and Bar 5 — all corresponding to the 300 Y-axis value;
例如,我想在第 3 条、第 4 条和第 5 条上画一条水平线——都对应 300 的 Y 轴值; 1 horizontal line on Bar 5 corresponding to the 600 Y-axis value;
第 5 条上的 1 条水平线对应 600 Y 轴值; 1 horizontal line on Bar 5 corresponding to the 900 Y-axis value.
条 5 上的 1 条水平线对应于 900 Y 轴值。
One way to do it would be like this:一种方法是这样的:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
fig_dims = (11, 8)
fig, ax = plt.subplots(figsize=fig_dims)
df = pd.DataFrame({'Group': ['Group 1', 'Group 2',
'Group 1', 'Group 2',
'Group 1', 'Group 2',
'Group 1', 'Group 2',
'Group 1', 'Group 2'],
'Bars': ['Bar 1', 'Bar 1',
'Bar 2', 'Bar 2',
'Bar 3', 'Bar 3',
'Bar 4', 'Bar 4',
'Bar 5', 'Bar 5'],
'Size': [300, 300,
300, 300,
600, 600,
600, 600,
1200, 1200]})
lines_1 = pd.DataFrame({'Values': [0, 0,
300, 300,
300, 300,
300, 300,
300, 300]})
lines_2 = pd.DataFrame({'Values': [0, 0,
0, 0,
600, 600,
600, 600,
600, 600]})
lines_3 = pd.DataFrame({'Values': [0, 0,
0, 0,
0, 0,
0, 0,
900, 900]})
sns.barplot(x='Group', y='Size', hue='Bars', data=df,
palette=['silver', 'cornflowerblue', 'royalblue', 'gold', 'darkgoldenrod'],
ax=ax, edgecolor='black', linewidth=0.4)
plt.title('Group bar chart plot with horizontal lines drawn on each bar')
plt.ylabel('Dataset size')
y = np.array([0, 1200])
ticks = np.arange(y.min(), y.max()+10, 300.0)
plt.yticks(ticks)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
horizontal_lines = [lines_1, lines_2, lines_3]
for lines in horizontal_lines:
for ix, a in enumerate(ax.patches):
x_start = a.get_x()
width = a.get_width()
ax.plot([x_start, x_start + width], 2 * [lines.loc[ix, 'Values']], '-', c='black', linewidth=0.4)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.