簡體   English   中英

Matplotlib如何調整點位置

[英]Matplotlib how to adjust point position

我有一個帶有第二條軸的水平條形圖,其中有一條線圖。 線圖的點不在條的中心,如下所示。

我試圖調整點的y值[v-0.5 for v in axes.get_yticks()]不會影響位置。 我不知道為什么。

在此處輸入圖片說明

這是代碼段:

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 ,則繪圖將如下所示

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM