gpt4 book ai didi

python - 如何在python中为列表绘制条形图

转载 作者:太空狗 更新时间:2023-10-30 00:39:29 25 4
gpt4 key购买 nike

我的列表是这样的

top = [('a',1.875),('c',1.125),('d',0.5)]

谁能帮我绘制 x 轴为 a、c、d 和 y 轴值为 1.875、1.125、0.5 的条形图?

我尝试使用以下代码进行绘图。

import numpy as np
import matplotlib.pyplot as plt

top = [('a',1.875),('c',1.125),('d',0.5)]

labels, values = zip(*top)
indexes = np.arange(len(labels))
width = 1

plt.bar(indexes, values, width)
plt.xticks(indexes + width * 0.5, labels)
plt.savefig('netscore.png')

我可以绘制条形图,但图表中的 y 轴值是错误的。

最佳答案

改变这一行:

import numpy

到:

import numpy as np

改变这一行:

labels, values = zip(*top[])

到:

labels, values = zip(*top)

排除了这些错误:

使用 axes 方法:

import numpy as np                                                               
import matplotlib.pyplot as plt

top=[('a',1.875),('c',1.125),('d',0.5)]

labels, ys = zip(*top)
xs = np.arange(len(labels))
width = 1

fig = plt.figure()
ax = fig.gca() #get current axes
ax.bar(xs, ys, width, align='center')

#Remove the default x-axis tick numbers and
#use tick numbers of your own choosing:
ax.set_xticks(xs)
#Replace the tick numbers with strings:
ax.set_xticklabels(labels)
#Remove the default y-axis tick numbers and
#use tick numbers of your own choosing:
ax.set_yticks(ys)

plt.savefig('netscore.png')

使用 plt 方法:

import numpy as np                                                               
import matplotlib.pyplot as plt

top=[('a',1.875),('c',1.125),('d',0.5)]

labels, ys = zip(*top)
xs = np.arange(len(labels))
width = 1

plt.bar(xs, ys, width, align='center')

plt.xticks(xs, labels) #Replace default x-ticks with xs, then replace xs with labels
plt.yticks(ys)

plt.savefig('netscore.png')

enter image description here

关于python - 如何在python中为列表绘制条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34029865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com