[英]Matplotlib how to adjust point position
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. 我试图调整点的y值
[v-0.5 for v in axes.get_yticks()]
不会影响位置。 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
[0, 1, 2, ...., 9]
,即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 如果使用
show_y_value=True
,则绘图将如下所示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.