I have a horizontal barplot with a 2nd axis that has a line plot. The dots of the lineplot is not centered with the bars as you can see below.
I tried to adjust the y value of the dots [v-0.5 for v in axes.get_yticks()]
which dose not affect the position. I don't know why that is.
Here is the snippet:
from random import randint
import numpy as np
import matplotlib.pyplot as plt
from typing import List, Dict
import seaborn as sns
def draw_barh_charts(
y_vals,
colors,
brands,
highlight_pos,
lines_y,
show_y_value=True,
rotation=0
):
# sns.set_style("whitegrid", {"axes.grid": False, "font.sans-serif": [cur_font]})
y_pos = np.arange(0,len(brands))
fig, axes = plt.subplots(figsize=(4, 8), dpi=100, sharey=True)
patches = []
for i, v in enumerate(y_vals):
bars = axes.barh(y_pos[i], v)
for j in range(len(bars)):
bars[j].set_color(colors[1] if i==highlight_pos else colors[0])
axes.set_yticks(y_pos)
axes.set_yticklabels(
brands, fontsize=16, rotation=rotation
)
axes.get_xaxis().set_visible(show_y_value)
ax = axes.twinx()
plt.plot(lines_y,
[v-0.5 for v in axes.get_yticks()], # adjusting here doesn't work
color='yellow',
marker='o'
)
ax.yaxis.set_tick_params(labelsize=16)
ax.axes.get_yaxis().set_visible(show_y_value)
sns.despine()
plt.show()
m = [10]*10
n = [randint(0,10) for x in range(10)]
colors = ['#C0C0C0','#62B2DA']
draw_barh_charts(m,
colors,
['A']*10,
0,
n,
rotation = 0,
show_y_value=False)
What you need is the following:
[0, 1, 2, ...., 9]
, ie, y_pos
def draw_barh_charts(y_vals, colors, brands, highlight_pos, lines_y, show_y_value=True, rotation=0):
y_pos = np.arange(0,len(brands))
fig, axes = plt.subplots(figsize=(4, 8), dpi=100, sharey=True)
patches = []
for i, v in enumerate(y_vals):
bars = axes.barh(y_pos[i], v)
for j in range(len(bars)):
bars[j].set_color(colors[1] if i==highlight_pos else colors[0])
axes.set_yticks(y_pos)
axes.set_yticklabels(brands, fontsize=16, rotation=rotation)
axes.get_xaxis().set_visible(show_y_value)
ax = axes.twinx()
plt.plot(lines_y, y_pos, # <--- Use correct y-values
color='yellow', marker='o')
ax.yaxis.set_tick_params(labelsize=16)
ax.axes.get_yaxis().set_visible(show_y_value)
ax.set_ylim(axes.get_ylim()) # <--- Align both y-axes
sns.despine()
plt.show()
If you use show_y_value=True
, this is how the plot will then look like
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.