python - Matplotlib如何调整点位置
问题描述
我有一个带有第二个轴的水平条形图,它有一个线图。如下所示,线图的点不以条为中心。
我试图调整[v-0.5 for v in axes.get_yticks()]
不影响位置的点的 y 值。我不知道为什么会这样。
这是片段:
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)
解决方案
您需要的是以下内容:
- 使用正确的 y 值范围来绘制线,
[0, 1, 2, ...., 9]
即 ,即y_pos
- 将右侧 y 轴的 y 限制与左侧 y 轴的 y 限制对齐
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()
如果你使用show_y_value=True
,这就是情节的样子
推荐阅读
- sql - 需要使用 max() 过滤列表
- php - PHP读取文本文件忽略特定选项卡
- javascript - jQuery UI - 防止对话框拖到 div 上方
- javascript - 如何仅使用 Javascript 从 JPEG 文件中获取 TIFF 标签?
- java - 如何使用密钥文件通过 Java 数据库连接连接到 AWS 数据库
- python-3.x - 如何从上面的嵌套文件夹中正确导入?
- javascript - 如何重构此代码以减少重复性?
- javascript - Noob 在链接 javascript 和 html 方面需要帮助
- c# - 如何将数组添加到 Mongo 实体类?
- eclipse - 我可以将 Wildfly 14 与 Eclipse Oxygen.3a 一起使用吗