sourcecode

사전을 사용하여 matplotlib를 사용하여 막대 그림 그리기

codebag 2023. 7. 22. 09:59
반응형

사전을 사용하여 matplotlib를 사용하여 막대 그림 그리기

다음을 사용하여 막대 그림을 그리는 방법이 있습니까?matplotlib딕트에서 직접 데이터를 사용합니까?

내 딕트는 다음과 같습니다.

D = {u'Label1':26, u'Label2': 17, u'Label3':30}

나는 예상했습니다.

fig = plt.figure(figsize=(5.5,3),dpi=300)
ax = fig.add_subplot(111)
bar = ax.bar(D,range(1,len(D)+1,1),0.5)

일을 하기 위해, 하지만 그렇지 않습니다.

다음은 오류입니다.

>>> ax.bar(D,range(1,len(D)+1,1),0.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/matplotlib/axes.py", line 4904, in bar
    self.add_patch(r)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/axes.py", line 1570, in add_patch
    self._update_patch_limits(p)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/axes.py", line 1588, in _update_patch_limits
    xys = patch.get_patch_transform().transform(vertices)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/patches.py", line 580, in get_patch_transform
    self._update_patch_transform()
  File "/usr/local/lib/python2.7/site-packages/matplotlib/patches.py", line 576, in _update_patch_transform
    bbox = transforms.Bbox.from_bounds(x, y, width, height)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/transforms.py", line 786, in from_bounds
    return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
TypeError: coercing to Unicode: need string or buffer, float found

먼저 막대 차트를 표시한 다음 적절한 눈금을 설정하여 두 줄로 나눌 수 있습니다.

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}

plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
# # for python 2.x:
# plt.bar(range(len(D)), D.values(), align='center')  # python 2.x
# plt.xticks(range(len(D)), D.keys())  # in python 2.x

plt.show()

끝이 없는 줄은 다음과 같아야 합니다.plt.xticks(range(len(D)), list(D.keys()))python3에서, 왜냐하면.D.keys()matplotlib에서 직접 사용할 수 없는 생성기를 반환합니다.

대부분의 답변이 제시하는 것보다 조금 더 간단합니다.

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(*zip(*D.items()))
plt.show()

enter image description here

향후 참조를 위해 위의 코드는 Python 3에서 작동하지 않습니다.Python 3의 경우,D.keys()목록으로 변환해야 합니다.

import matplotlib.pyplot as plt

D = {u'Label1':26, u'Label2': 17, u'Label3':30}

plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), list(D.keys()))

plt.show()

왜 그냥:

names, counts = zip(*D.items())
plt.bar(names, counts)

enter image description here

를 사용하여 구현하는 가장 좋은 방법matplotlib.pyplot.bar(range, height, tick_label)여기서 범위는 그래프에서 해당 막대의 위치를 지정하기 위한 스칼라 값을 제공합니다.tick_label와 동일하게 작동합니다.xticks()정수로 바꿀 수도 있고 여러 개를 사용할 수도 있습니다.plt.bar(integer, height, tick_label)자세한 내용은 설명서를 참조하십시오.

import matplotlib.pyplot as plt

data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())

#tick_label does the some work as plt.xticks()
plt.bar(range(len(data)),values,tick_label=names)
plt.savefig('bar.png')
plt.show()

enter image description here

또한 다음을 사용하지 않고도 동일한 그림을 생성할 수 있습니다.range()하지만 마주친 문제는tick_label방금 마지막으로 일했습니다.plt.bar()콜. 그러므로xticks()라벨링에 사용되었습니다.

data = {'apple': 67, 'mango': 60, 'lichi': 58}
names = list(data.keys())
values = list(data.values())
plt.bar(0,values[0],tick_label=names[0])
plt.bar(1,values[1],tick_label=names[1])
plt.bar(2,values[2],tick_label=names[2])
plt.xticks(range(0,3),names)
plt.savefig('fruit.png')
plt.show()

enter image description here

저는 종종 dict를 판다 데이터 프레임에 로드한 다음 데이터 프레임의 플롯 기능을 사용합니다.
여기 한 줄기 선이 있습니다.

pandas.DataFrame(D, index=['quantity']).plot(kind='bar')

resulting plot

왜 그냥:

import seaborn as sns

sns.barplot(list(D.keys()), list(D.values()))

언급URL : https://stackoverflow.com/questions/16010869/plot-a-bar-using-matplotlib-using-a-dictionary

반응형