簡體   English   中英

使用matplotlib繪制條形圖 - 類型錯誤

[英]plot a bar chart using matplotlib - type error

我試圖繪制一個頻率分布(出現的詞及其頻率)

這是我的代碼:

import matplotlib.pyplot as plt

y = [1,2,3,4,5]
x = ['apple', 'orange', 'pear', 'mango', 'peach']

plt.bar(x,y)
plt.show

但是,我收到此錯誤:

TypeError: cannot concatenate 'str' and 'float' objects
import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
x = np.arange(0,len(y)) + 0.75
xl = ['', 'apple', 'orange', 'pear', 'mango', 'peach']

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5)
ax.set_xticklabels(xl)
ax.set_xlim(0,5.5)

如果有一種更好的方法可以將標簽設置在條形圖的中間,那將會很有趣。

根據這篇SO帖子 ,有一個更好的解決方案:

import matplotlib.pyplot as plt
import numpy as np
y = [1,2,3,4,5]
# adding 0.75 did the trick but only if I add a blank position to `xl`
x = np.arange(len(y))
xl = ['apple', 'orange', 'pear', 'mango', 'peach']

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x,y,0.5, align='center')
ax.set_xticks(x)
ax.set_xticklabels(xl)

只需添加兩行:

import matplotlib.pyplot as plt
y = [1, 2, 3, 4, 5]
x_name = ['apple', 'orange', 'pear', 'mango', 'peach']
x = np.arange(len(x_name))  # <--
plt.bar(x, y)
plt.xticks(x, x_name)  # <--
plt.show()

在此輸入圖像描述

v2.1中將直接支持繪圖plt.bar(x_name, y) ,請參見https://github.com/matplotlib/matplotlib/issues/8959

暫無
暫無

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

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