从字典中绘制直方图时出错
Error in plotting histogram from dictionary
我有一个包含 7191
个键的字典,值代表每个键的出现频率。
degree_distri = {'F2': 102, 'EGFR': 23, 'C1R': 20,...}
为了绘制直方图,我做了:
plt.bar(list(degree_distri.keys()), degree_distri.values(), color='r')
但我收到此错误消息:
unsupported operand type(s) for -: 'str' and 'float'
我不应该使用上面的代码来绘制直方图吗?如果没有,会有哪些建议?为什么会导致错误?
谢谢!
看这个例子here and the documentation你必须
以不同的格式提供您的数据。
import matplotlib.pyplot as plt
import numpy as np
degree_distri = {'F2': 102, 'EGFR': 23, 'C1R': 20}
fig, ax = plt.subplots()
indices = np.arange(len(degree_distri))
width = 0.6
ax.bar(indices, degree_distri.values(), width)
ax.set_xticks(indices)
ax.set_xticklabels(degree_distri.keys())
首先设置条形的左侧 x 坐标,使用 indices
完成,一个包含数字 0 到 dict
长度的数组。然后提供值。 dict
中的 keys
必须设置为轴标签,并且要将轴标签定位在正确的位置,您必须使用条的 x 位置调用 set_xticks
。
matplotlib.pyplot.bar
takes as obligatory paramaters two sequence of scalars: the x coordinates of the left sides of the bars and the heights of the bars. So you should use range
to get the paramater needed, and then use plt.xticks
设置您想要的报价:
import matplotlib.pyplot as plt
degree_distri = {'F2': 102, 'EGFR': 23, 'C1R': 20}
keys, values = degree_distri.keys(), degree_distri.values()
plt.bar(range(len(values)), values, color='r')
plt.xticks(range(len(values)), keys)
plt.show()
我有一个包含 7191
个键的字典,值代表每个键的出现频率。
degree_distri = {'F2': 102, 'EGFR': 23, 'C1R': 20,...}
为了绘制直方图,我做了:
plt.bar(list(degree_distri.keys()), degree_distri.values(), color='r')
但我收到此错误消息:
unsupported operand type(s) for -: 'str' and 'float'
我不应该使用上面的代码来绘制直方图吗?如果没有,会有哪些建议?为什么会导致错误?
谢谢!
看这个例子here and the documentation你必须 以不同的格式提供您的数据。
import matplotlib.pyplot as plt
import numpy as np
degree_distri = {'F2': 102, 'EGFR': 23, 'C1R': 20}
fig, ax = plt.subplots()
indices = np.arange(len(degree_distri))
width = 0.6
ax.bar(indices, degree_distri.values(), width)
ax.set_xticks(indices)
ax.set_xticklabels(degree_distri.keys())
首先设置条形的左侧 x 坐标,使用 indices
完成,一个包含数字 0 到 dict
长度的数组。然后提供值。 dict
中的 keys
必须设置为轴标签,并且要将轴标签定位在正确的位置,您必须使用条的 x 位置调用 set_xticks
。
matplotlib.pyplot.bar
takes as obligatory paramaters two sequence of scalars: the x coordinates of the left sides of the bars and the heights of the bars. So you should use range
to get the paramater needed, and then use plt.xticks
设置您想要的报价:
import matplotlib.pyplot as plt
degree_distri = {'F2': 102, 'EGFR': 23, 'C1R': 20}
keys, values = degree_distri.keys(), degree_distri.values()
plt.bar(range(len(values)), values, color='r')
plt.xticks(range(len(values)), keys)
plt.show()