如何基于非零值绘制图条

问题描述 投票:0回答:1

通常,条形图的底部显示为零。改变底部时,栏会向上或向下移动。

import numpy as np
import matplotlib.pyplot as plt


N = 5
menMeans   = (20, 35, 30, 35, 27)

ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, bottom=0,color='#d62728')

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend('Men')
plt.savefig('bar.png')
plt.show()

当我想要不向上或向下移动时。以下代码显示了零的底数。

我想基于诸如25之类的值显示图表。如果数据诸如20,则它在图表中25之下显示5。the chart I want to get

python matplotlib
1个回答
0
投票

您可以将menMeans转换为numpy menMeans = np.array(menMeans),然后减去底部。减去25,新数组将为[-5, 10, 5, 10, 2]

import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
menMeans = np.array(menMeans)


ind = np.arange(N)  # the x locations for the groups
width = 0.35  # the width of the bars: can also be len(x) sequence

bottom = 25
p1 = plt.bar(ind, menMeans-bottom, width, bottom=bottom, color='#d62728', label='Men')
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
ax = plt.gca()
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position(('data', bottom))
ax.spines['top'].set_color('none')
for i, mean in enumerate(menMeans):
    if mean >= bottom:
        ax.text(i, mean, f'{mean}\n', ha='center', va='center')
    else:
        ax.text(i, mean, f'\n{mean}', ha='center', va='center')

plt.legend()
plt.savefig('bar.png')
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.