python: plot a bar using matplotlib using a dictionary
Is there any way to plot a bar plot using matplotlib
using data directly from a dict?
My dict looks like this:
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
I was expecting
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)
to work, but it does not.
Here is the error:
>>> 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
python matplotlib plot
|
show 2 more comments
Is there any way to plot a bar plot using matplotlib
using data directly from a dict?
My dict looks like this:
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
I was expecting
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)
to work, but it does not.
Here is the error:
>>> 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
python matplotlib plot
Can you share specifically what does not work? Do you get an exception? What exception? Share as much information as possible.
– Inbar Rose
Apr 15 '13 at 8:38
@InbarRose sorry, I have updated the question with the error it shows... something concerning string or buffer... I don't understand this error message.
– otmezger
Apr 15 '13 at 8:40
2
It's not clear what you want to achieve, but inax.bar(D,range(1,len(D)+1,1),0.5)
the first argument should be a list of numbers, in your caseD.values()
.
– adrianp
Apr 15 '13 at 8:43
2
A one-liner is not possible for this, at least to my knowledge.
– adrianp
Apr 15 '13 at 9:03
1
You might want to submit a feature request to the github site for this, because it does seem useful.
– tacaswell
Apr 15 '13 at 16:05
|
show 2 more comments
Is there any way to plot a bar plot using matplotlib
using data directly from a dict?
My dict looks like this:
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
I was expecting
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)
to work, but it does not.
Here is the error:
>>> 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
python matplotlib plot
Is there any way to plot a bar plot using matplotlib
using data directly from a dict?
My dict looks like this:
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
I was expecting
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)
to work, but it does not.
Here is the error:
>>> 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
python matplotlib plot
python matplotlib plot
edited Apr 15 '13 at 8:39
asked Apr 15 '13 at 8:34
otmezger
3,468134175
3,468134175
Can you share specifically what does not work? Do you get an exception? What exception? Share as much information as possible.
– Inbar Rose
Apr 15 '13 at 8:38
@InbarRose sorry, I have updated the question with the error it shows... something concerning string or buffer... I don't understand this error message.
– otmezger
Apr 15 '13 at 8:40
2
It's not clear what you want to achieve, but inax.bar(D,range(1,len(D)+1,1),0.5)
the first argument should be a list of numbers, in your caseD.values()
.
– adrianp
Apr 15 '13 at 8:43
2
A one-liner is not possible for this, at least to my knowledge.
– adrianp
Apr 15 '13 at 9:03
1
You might want to submit a feature request to the github site for this, because it does seem useful.
– tacaswell
Apr 15 '13 at 16:05
|
show 2 more comments
Can you share specifically what does not work? Do you get an exception? What exception? Share as much information as possible.
– Inbar Rose
Apr 15 '13 at 8:38
@InbarRose sorry, I have updated the question with the error it shows... something concerning string or buffer... I don't understand this error message.
– otmezger
Apr 15 '13 at 8:40
2
It's not clear what you want to achieve, but inax.bar(D,range(1,len(D)+1,1),0.5)
the first argument should be a list of numbers, in your caseD.values()
.
– adrianp
Apr 15 '13 at 8:43
2
A one-liner is not possible for this, at least to my knowledge.
– adrianp
Apr 15 '13 at 9:03
1
You might want to submit a feature request to the github site for this, because it does seem useful.
– tacaswell
Apr 15 '13 at 16:05
Can you share specifically what does not work? Do you get an exception? What exception? Share as much information as possible.
– Inbar Rose
Apr 15 '13 at 8:38
Can you share specifically what does not work? Do you get an exception? What exception? Share as much information as possible.
– Inbar Rose
Apr 15 '13 at 8:38
@InbarRose sorry, I have updated the question with the error it shows... something concerning string or buffer... I don't understand this error message.
– otmezger
Apr 15 '13 at 8:40
@InbarRose sorry, I have updated the question with the error it shows... something concerning string or buffer... I don't understand this error message.
– otmezger
Apr 15 '13 at 8:40
2
2
It's not clear what you want to achieve, but in
ax.bar(D,range(1,len(D)+1,1),0.5)
the first argument should be a list of numbers, in your case D.values()
.– adrianp
Apr 15 '13 at 8:43
It's not clear what you want to achieve, but in
ax.bar(D,range(1,len(D)+1,1),0.5)
the first argument should be a list of numbers, in your case D.values()
.– adrianp
Apr 15 '13 at 8:43
2
2
A one-liner is not possible for this, at least to my knowledge.
– adrianp
Apr 15 '13 at 9:03
A one-liner is not possible for this, at least to my knowledge.
– adrianp
Apr 15 '13 at 9:03
1
1
You might want to submit a feature request to the github site for this, because it does seem useful.
– tacaswell
Apr 15 '13 at 16:05
You might want to submit a feature request to the github site for this, because it does seem useful.
– tacaswell
Apr 15 '13 at 16:05
|
show 2 more comments
5 Answers
5
active
oldest
votes
You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:
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()
Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys())) in python3, because D.keys() returns a generator, which matplotlib cannot use directly.
2
you can of course wrap those two lines up in a function and then it becomes a one-liner ;)
– tacaswell
Apr 15 '13 at 16:04
2
If you use figure and axes objects, it'sax.set_xticklabels
– Mark
Jan 13 '14 at 5:41
1
thanks! But I have some estetic issues with plt.xticks, could you please tell us how to move them vertically from horizontally.
– moldovean
Mar 11 '14 at 14:58
2
are the key-value pairs aligned when the dict is not sorted?
– ssm
Mar 18 '15 at 5:46
1
Python dicts cannot be sorted. Consequently, the order is always arbitrary. However, the keys and values are always aligned with the above code.
– David Zwicker
Mar 18 '15 at 18:03
|
show 6 more comments
For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list.
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()
add a comment |
The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label)
where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label
does the same work as xticks()
. One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label)
. For detailed information please refer the documentation.
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()
Additionally the same plot can be generated without using range()
. But the problem encountered was that tick_label
just worked for the last plt.bar()
call. Hence xticks()
was used for labelling:
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()
add a comment |
I often load the dict into a pandas DataFrame then use the plot function of the DataFrame.
Here is the one-liner:
pandas.DataFrame(D, index=['quantity']).plot(kind='bar')
add a comment |
It's a little simpler than most answers here suggest:
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(*zip(*D.items()))
plt.show()
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16010869%2fpython-plot-a-bar-using-matplotlib-using-a-dictionary%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:
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()
Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys())) in python3, because D.keys() returns a generator, which matplotlib cannot use directly.
2
you can of course wrap those two lines up in a function and then it becomes a one-liner ;)
– tacaswell
Apr 15 '13 at 16:04
2
If you use figure and axes objects, it'sax.set_xticklabels
– Mark
Jan 13 '14 at 5:41
1
thanks! But I have some estetic issues with plt.xticks, could you please tell us how to move them vertically from horizontally.
– moldovean
Mar 11 '14 at 14:58
2
are the key-value pairs aligned when the dict is not sorted?
– ssm
Mar 18 '15 at 5:46
1
Python dicts cannot be sorted. Consequently, the order is always arbitrary. However, the keys and values are always aligned with the above code.
– David Zwicker
Mar 18 '15 at 18:03
|
show 6 more comments
You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:
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()
Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys())) in python3, because D.keys() returns a generator, which matplotlib cannot use directly.
2
you can of course wrap those two lines up in a function and then it becomes a one-liner ;)
– tacaswell
Apr 15 '13 at 16:04
2
If you use figure and axes objects, it'sax.set_xticklabels
– Mark
Jan 13 '14 at 5:41
1
thanks! But I have some estetic issues with plt.xticks, could you please tell us how to move them vertically from horizontally.
– moldovean
Mar 11 '14 at 14:58
2
are the key-value pairs aligned when the dict is not sorted?
– ssm
Mar 18 '15 at 5:46
1
Python dicts cannot be sorted. Consequently, the order is always arbitrary. However, the keys and values are always aligned with the above code.
– David Zwicker
Mar 18 '15 at 18:03
|
show 6 more comments
You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:
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()
Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys())) in python3, because D.keys() returns a generator, which matplotlib cannot use directly.
You can do it in two lines by first plotting the bar chart and then setting the appropriate ticks:
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()
Note that the penultimate line should read plt.xticks(range(len(D)), list(D.keys())) in python3, because D.keys() returns a generator, which matplotlib cannot use directly.
edited Dec 9 '17 at 7:33
wp78de
9,83951738
9,83951738
answered Apr 15 '13 at 12:13
David Zwicker
14.6k44263
14.6k44263
2
you can of course wrap those two lines up in a function and then it becomes a one-liner ;)
– tacaswell
Apr 15 '13 at 16:04
2
If you use figure and axes objects, it'sax.set_xticklabels
– Mark
Jan 13 '14 at 5:41
1
thanks! But I have some estetic issues with plt.xticks, could you please tell us how to move them vertically from horizontally.
– moldovean
Mar 11 '14 at 14:58
2
are the key-value pairs aligned when the dict is not sorted?
– ssm
Mar 18 '15 at 5:46
1
Python dicts cannot be sorted. Consequently, the order is always arbitrary. However, the keys and values are always aligned with the above code.
– David Zwicker
Mar 18 '15 at 18:03
|
show 6 more comments
2
you can of course wrap those two lines up in a function and then it becomes a one-liner ;)
– tacaswell
Apr 15 '13 at 16:04
2
If you use figure and axes objects, it'sax.set_xticklabels
– Mark
Jan 13 '14 at 5:41
1
thanks! But I have some estetic issues with plt.xticks, could you please tell us how to move them vertically from horizontally.
– moldovean
Mar 11 '14 at 14:58
2
are the key-value pairs aligned when the dict is not sorted?
– ssm
Mar 18 '15 at 5:46
1
Python dicts cannot be sorted. Consequently, the order is always arbitrary. However, the keys and values are always aligned with the above code.
– David Zwicker
Mar 18 '15 at 18:03
2
2
you can of course wrap those two lines up in a function and then it becomes a one-liner ;)
– tacaswell
Apr 15 '13 at 16:04
you can of course wrap those two lines up in a function and then it becomes a one-liner ;)
– tacaswell
Apr 15 '13 at 16:04
2
2
If you use figure and axes objects, it's
ax.set_xticklabels
– Mark
Jan 13 '14 at 5:41
If you use figure and axes objects, it's
ax.set_xticklabels
– Mark
Jan 13 '14 at 5:41
1
1
thanks! But I have some estetic issues with plt.xticks, could you please tell us how to move them vertically from horizontally.
– moldovean
Mar 11 '14 at 14:58
thanks! But I have some estetic issues with plt.xticks, could you please tell us how to move them vertically from horizontally.
– moldovean
Mar 11 '14 at 14:58
2
2
are the key-value pairs aligned when the dict is not sorted?
– ssm
Mar 18 '15 at 5:46
are the key-value pairs aligned when the dict is not sorted?
– ssm
Mar 18 '15 at 5:46
1
1
Python dicts cannot be sorted. Consequently, the order is always arbitrary. However, the keys and values are always aligned with the above code.
– David Zwicker
Mar 18 '15 at 18:03
Python dicts cannot be sorted. Consequently, the order is always arbitrary. However, the keys and values are always aligned with the above code.
– David Zwicker
Mar 18 '15 at 18:03
|
show 6 more comments
For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list.
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()
add a comment |
For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list.
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()
add a comment |
For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list.
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()
For future reference, the above code does not work with Python 3. For Python 3, the D.keys() needs to be converted to a list.
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()
answered Mar 18 '15 at 5:25
Michael T
56549
56549
add a comment |
add a comment |
The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label)
where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label
does the same work as xticks()
. One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label)
. For detailed information please refer the documentation.
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()
Additionally the same plot can be generated without using range()
. But the problem encountered was that tick_label
just worked for the last plt.bar()
call. Hence xticks()
was used for labelling:
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()
add a comment |
The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label)
where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label
does the same work as xticks()
. One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label)
. For detailed information please refer the documentation.
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()
Additionally the same plot can be generated without using range()
. But the problem encountered was that tick_label
just worked for the last plt.bar()
call. Hence xticks()
was used for labelling:
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()
add a comment |
The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label)
where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label
does the same work as xticks()
. One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label)
. For detailed information please refer the documentation.
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()
Additionally the same plot can be generated without using range()
. But the problem encountered was that tick_label
just worked for the last plt.bar()
call. Hence xticks()
was used for labelling:
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()
The best way to implement it using matplotlib.pyplot.bar(range, height, tick_label)
where the range provides scalar values for the positioning of the corresponding bar in the graph. tick_label
does the same work as xticks()
. One can replace it with an integer also and use multiple plt.bar(integer, height, tick_label)
. For detailed information please refer the documentation.
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()
Additionally the same plot can be generated without using range()
. But the problem encountered was that tick_label
just worked for the last plt.bar()
call. Hence xticks()
was used for labelling:
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()
edited Jan 26 at 4:25
Stephen Rauch
27.6k153256
27.6k153256
answered Jan 26 at 3:56
Swaraj Kumar
11414
11414
add a comment |
add a comment |
I often load the dict into a pandas DataFrame then use the plot function of the DataFrame.
Here is the one-liner:
pandas.DataFrame(D, index=['quantity']).plot(kind='bar')
add a comment |
I often load the dict into a pandas DataFrame then use the plot function of the DataFrame.
Here is the one-liner:
pandas.DataFrame(D, index=['quantity']).plot(kind='bar')
add a comment |
I often load the dict into a pandas DataFrame then use the plot function of the DataFrame.
Here is the one-liner:
pandas.DataFrame(D, index=['quantity']).plot(kind='bar')
I often load the dict into a pandas DataFrame then use the plot function of the DataFrame.
Here is the one-liner:
pandas.DataFrame(D, index=['quantity']).plot(kind='bar')
answered Mar 1 at 17:07
anilbey
65921027
65921027
add a comment |
add a comment |
It's a little simpler than most answers here suggest:
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(*zip(*D.items()))
plt.show()
add a comment |
It's a little simpler than most answers here suggest:
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(*zip(*D.items()))
plt.show()
add a comment |
It's a little simpler than most answers here suggest:
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(*zip(*D.items()))
plt.show()
It's a little simpler than most answers here suggest:
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(*zip(*D.items()))
plt.show()
answered Nov 22 at 13:35
ImportanceOfBeingErnest
125k10127203
125k10127203
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f16010869%2fpython-plot-a-bar-using-matplotlib-using-a-dictionary%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Can you share specifically what does not work? Do you get an exception? What exception? Share as much information as possible.
– Inbar Rose
Apr 15 '13 at 8:38
@InbarRose sorry, I have updated the question with the error it shows... something concerning string or buffer... I don't understand this error message.
– otmezger
Apr 15 '13 at 8:40
2
It's not clear what you want to achieve, but in
ax.bar(D,range(1,len(D)+1,1),0.5)
the first argument should be a list of numbers, in your caseD.values()
.– adrianp
Apr 15 '13 at 8:43
2
A one-liner is not possible for this, at least to my knowledge.
– adrianp
Apr 15 '13 at 9:03
1
You might want to submit a feature request to the github site for this, because it does seem useful.
– tacaswell
Apr 15 '13 at 16:05