matplotlib 如何在条形图中的某个条形未赋值时居中显示条形

vjrehmav  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(191)

我的问题是其中一个酒吧不是居中的,因为酒吧可能是旁边的技术(它是没有)是某种程度上干扰或可能不是我不知道。
我的密码是:

import matplotlib.pyplot as plt

# Define the data
categories = ['bear', 'neutral', 'man']
wins = [2, 3, 7]
attacks = [3, None, 5]

# Create a bar chart
fig, ax = plt.subplots()

ax.bar(categories, wins, 0.35, label='Win')
ax.bar([i + 0.35 for i in range(len(attacks)) if attacks[i] is not None],
                list(filter(None, attacks)), 0.35, label='Attack')

# Add labels and legend
ax.set_xticks([i + 0.35/2 for i in range(len(categories))])
ax.legend()

# Display the chart
plt.show()

问题是这张图表

这是我想要的(中间的酒吧是居中的图片):

9udxz4iz

9udxz4iz1#

下面的方法不是很通用,但对你的情况很有效。当没有第二个柱时,第一个柱的位置会被修改。刻度标签与刻度位置同时设置。

import matplotlib.pyplot as plt

# Define the data
categories = ['bear', 'neutral', 'man']
wins = [2, 3, 7]
attacks = [3, None, 5]

# Create a bar chart
fig, ax = plt.subplots()

ax.bar([i + (0.35 / 2 if attacks[i] is None else 0) for i in range(len(attacks))],
       wins, 0.35, label='Win')
ax.bar([i + 0.35 for i in range(len(attacks)) if attacks[i] is not None],
       list(filter(None, attacks)), 0.35, label='Attack')

# Add labels and legend
ax.set_xticks([i + 0.35 / 2 for i in range(len(categories))], categories)
ax.legend()

# Display the chart
plt.show()

另一个想法是使用numpy对位置进行数组操作,当数据转换为numpy数组时,float类型将None表示为NaN

import matplotlib.pyplot as plt
import numpy as np

# Define the data
categories = ['bear', 'neutral', 'man']
wins = [2, 3, 7]
attacks = [3, None, 5]

# Create a bar chart
fig, ax = plt.subplots()

# convert to numpy arrays of type float, representing None with NaN
wins = np.array(wins, dtype=float)
attacks = np.array(attacks, dtype=float)

# positions for the ticks
pos = np.arange(len(categories))

# delta change on the ticks depending on a win or an attack being NaN
delta = np.where(np.isnan(wins) | np.isnan(attacks), 0, 0.35/2)

# draw the bars, once using -delta and once +delta for the positions
ax.bar(pos - delta, wins, 0.35, label='Win')
ax.bar(pos + delta, attacks, 0.35, label='Attack')

# Add labels and legend
ax.set_xticks(pos, categories)
ax.legend()

plt.show()

相关问题