如何使用条形图作为“温度计”?

2024-05-20 01:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个Python脚本来提取评论中的情感。现在我想用三个步骤来表达总体情绪:消极、中立和积极。我想用一个条形图,但只有一个条形图作为温度计(条形图越高,评论就越好),但我有点卡住了

import matplotlib.pyplot as plt
import numpy as np

# Bar chart
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
emotion = ['Negative', 'Neutral', 'Positive']
percentage = [23,17,60]
width = 0.35

ax.bar(emotion,percentage)
ax.set_ylabel('Positivity')
ax.set_title('General emotion in comments')

# here it's wrong but I don't know how to perform what I want
ax.bar(1, percentage[0], width, color='r')  
ax.bar(1, percentage[1], width, color='b')  
ax.bar(1, percentage[2], width, color='g')  
###############################################
ax.set_yticks(np.arange(-100, 100, 10))
plt.show()  

在这种情况下,我硬编码的意见是23%的负面,17%的中立和60%的积极,但我不知道如何:

  • 打印轴信息(此处为正)
  • 使用我的percentage来绘制条,因为目前我有三种条,但我想要一条

我要创建的条形图如下所示:

enter image description here

谢谢你的帮助

[编辑]

好的,我对代码做了一些修改:

fig, ax = plt.subplots(figsize=(12, 6))
emotion = ['Negative', 'Neutral', 'Positive']
percentage = [-23,17,60]
plt.title('General emotion in comments')
plt.xlabel(' ')
plt.ylabel('Positivity')
plt.ylim([-100, 100])
ax.bar(2, percentage[2], width=0.35, color='g')
ax.bar(2, percentage[0], width=0.35, color='r')
plt.show()

Tags: importasnp评论figbarpltax
1条回答
网友
1楼 · 发布于 2024-05-20 01:33:04

在我提供了这么多帮助之后

x = 1   
fig, ax = plt.subplots(figsize=(12, 6))

emotion = ['Negative', 'Neutral', 'Positive']
percentage = [-23,17,60]
plt.title('General emotion')
plt.ylabel('Positivity')
plt.ylim([-100, 100])
ax.set_xlim(0,3)
plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)


ax.bar(x, percentage[2], width=0.35, color='g')
ax.bar(x, percentage[0], width=0.35, color='r')
plt.show()

相关问题 更多 >