I am struggling with this really badly. There is something that I'm just not getting. I have a function, which I want to plot a histogram of a dictionary with the keys on the x-axis and the values on the y-axis, then save the file in a location specified when calling the function. What I have is:
import matplotlib.pyplot as plt
def test(filename):
dictionary = {0:1000, 1:20, 2:15, 3:0, 4:5}
xmax = max(dictionary.keys())
ymax = max(dictionary.values())
plt.hist(dictionary,xmax)
plt.title('Histogram Title')
plt.xlabel('Label')
plt.ylabel('Another Label')
plt.axis([0, xmax, 0, ymax])
plt.figure()
plt.savefig(filename)
test('test_graph.svg')
I simply cannot get this to work, and I've struggled for a very long time reading other questions and documentation. Any help would be greatly appreciated. Thanks.
EDIT:
The error I have is:
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 343, in figure
**kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
window = Tk.Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1688, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
TclError: no display name and no $DISPLAY environment variable
You are getting snarled up by the state-machine interface:
import matplotlib.pyplot as plt
def test(filename):
dictionary = {0:1000, 1:20, 2:15, 3:0, 4:5}
xmax = max(dictionary.keys())
ymax = max(dictionary.values())
plt.figure() # <- makes a new figure and sets it active (add this)
plt.hist(dictionary,xmax) # <- finds the current active axes/figure and plots to it
plt.title('Histogram Title')
plt.xlabel('Label')
plt.ylabel('Another Label')
plt.axis([0, xmax, 0, ymax])
# plt.figure() # <- makes new figure and makes it active (remove this)
plt.savefig(filename) # <- saves the currently active figure (which is empty in your code)
test('test_graph.svg')
See How can I attach a pyplot function to a figure instance? for a longer explanation of the state-machine vs OO interfaces for matplotlib.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With