sblvr/StackOverFlow_DSLib
Dataset Card for Dataset Name This dataset card aims to be a base template for new datasets. It has been generated using this raw template. Dataset Details Dataset Description Curated by: [More Information Needed] Funded by [optional]: [More Information Needed] Shared by [optional]: [More Information Needed] Language(s) (NLP): [More Information Needed] License: [More Information Needed] Dataset Sources [optional]… See the full description on the dataset page: https://huggingface.co/datasets/sblvr/StackOverFlow_DSLib.
011
1[2 {3 "question":"How to make IPython notebook matplotlib plot inline I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0. I cannot get matplotlib graphics to show up inline. ``` import matplotlib import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference. ``` x = np.linspace(0, 3*np.pi, 500) plt.plot(x, np.sin(x**2)) plt.title('A simple chirp') plt.show() ``` Instead of inline graphics, I get this: ``` ``` And matplotlib.get_backend() shows that I have the 'module:\/\/IPython.kernel.zmq.pylab.backend_inline' backend.",4 "response":"I used %matplotlib inline in the first cell of the notebook and it works. I think you should try: ``` %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt ``` You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files: ``` c.IPKernelApp.matplotlib= Default: None Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx'] Configure matplotlib for interactive use with the default matplotlib backend. ```",5 "best_answers_score":0.8,6 "library_name":"matplotlib",7 "question_url":"https:\/\/stackoverflow.com\/questions\/19410042\/how-to-make-ipython-notebook-matplotlib-plot-inline",8 "best_answers_votes":1238,9 "question_length":665,10 "response_length":56111 },12 {13 "question":"How do I set the figure title and axes labels font size? I am creating a figure in Matplotlib like this: ```py from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title') plt.xlabel('xlabel') plt.ylabel('ylabel') fig.savefig('test.jpg') ``` I want to specify font sizes for the figure title and the axis labels. I need all three to be different font sizes, so setting a global font size (mpl.rcParams['font.size']=x) is not what I want. How do I set font sizes for the figure title and the axis labels individually?",14 "response":"Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size\/fontsize: ``` from matplotlib import pyplot as plt fig = plt.figure() plt.plot(data) fig.suptitle('test title', fontsize=20) plt.xlabel('xlabel', fontsize=18) plt.ylabel('ylabel', fontsize=16) fig.savefig('test.jpg') ``` For globally setting title and label sizes, mpl.rcParams contains axes.titlesize and axes.labelsize. (From the page): ``` axes.titlesize : large # fontsize of the axes title axes.labelsize : medium # fontsize of the x any y labels ``` (As far as I can see, there is no way to set x and y label sizes separately.) And I see that axes.titlesize does not affect suptitle. I guess, you need to set that manually.",15 "best_answers_score":0.8,16 "library_name":"matplotlib",17 "question_url":"https:\/\/stackoverflow.com\/questions\/12444716\/how-do-i-set-the-figure-title-and-axes-labels-font-size",18 "best_answers_votes":1262,19 "question_length":553,20 "response_length":76421 },22 {23 "question":"Changing the tick frequency on the x or y axis I am trying to fix how python plots my data. Say: ```py x = [0, 5, 9, 10, 15] y = [0, 1, 2, 3, 4] matplotlib.pyplot.plot(x, y) matplotlib.pyplot.show() ``` The x axis' ticks are plotted in intervals of 5. Is there a way to make it show intervals of 1?",24 "response":"You could explicitly set where you want to tick marks with plt.xticks: ``` plt.xticks(np.arange(min(x), max(x)+1, 1.0)) ``` For example, ``` import numpy as np import matplotlib.pyplot as plt x = [0,5,9,10,15] y = [0,1,2,3,4] plt.plot(x,y) plt.xticks(np.arange(min(x), max(x)+1, 1.0)) plt.show() ``` (np.arange was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints.) The plt.plot (or ax.plot) function will automatically set default x and y limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set. ``` start, end = ax.get_xlim() ax.xaxis.set_ticks(np.arange(start, end, stepsize)) ``` The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example, ``` ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f')) ``` Here's a runnable example: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker x = [0,5,9,10,15] y = [0,1,2,3,4] fig, ax = plt.subplots() ax.plot(x,y) start, end = ax.get_xlim() ax.xaxis.set_ticks(np.arange(start, end, 0.712123)) ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f')) plt.show() ```",25 "best_answers_score":0.8,26 "library_name":"matplotlib",27 "question_url":"https:\/\/stackoverflow.com\/questions\/12608788\/changing-the-tick-frequency-on-the-x-or-y-axis",28 "best_answers_votes":937,29 "question_length":298,30 "response_length":139831 },32 {33 "question":"When to use cla(), clf() or close() for clearing a plot Matplotlib offers these functions: ```py cla() # Clear axis clf() # Clear figure close() # Close a figure window ``` When should I use each function and what exactly does it do?",34 "response":"They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the Figure class. I will discuss both cases below. pyplot interface pyplot is a module that collects a couple of functions that allow matplotlib to be used in a functional manner. I here assume that pyplot has been imported as import matplotlib.pyplot as plt. In this case, there are three different commands that remove stuff: See matplotlib.pyplot Functions: plt.cla() clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched. plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots. plt.close() closes a window, which will be the current window, if not specified otherwise. Which functions suits you best depends thus on your use-case. The close() function furthermore allows one to specify which window should be closed. The argument can either be a number or name given to a window when it was created using figure(number_or_name) or it can be a figure instance fig obtained, i.e., usingfig = figure(). If no argument is given to close(), the currently active window will be closed. Furthermore, there is the syntax close('all'), which closes all figures. methods of the Figure class Additionally, the Figure class provides methods for clearing figures. I'll assume in the following that fig is an instance of a Figure: fig.clf() clears the entire figure. This call is equivalent to plt.clf() only if fig is the current figure. fig.clear() is a synonym for fig.clf() Note that even del fig will not close the associated figure window. As far as I know the only way to close a figure window is using plt.close(fig) as described above.",35 "best_answers_score":0.8,36 "library_name":"matplotlib",37 "question_url":"https:\/\/stackoverflow.com\/questions\/8213522\/when-to-use-cla-clf-or-close-for-clearing-a-plot",38 "best_answers_votes":960,39 "question_length":233,40 "response_length":189841 },42 {43 "question":"How do I change the figure size with subplots? How do I increase the figure size for this figure? This does nothing: ```py f.figsize(15, 15) ``` Example code from the link: ```py import matplotlib.pyplot as plt import numpy as np # Simple data to display in various forms x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) plt.close('all') # Just a figure and one subplot f, ax = plt.subplots() ax.plot(x, y) ax.set_title('Simple plot') # Two subplots, the axes array is 1-d f, axarr = plt.subplots(2, sharex=True) axarr[0].plot(x, y) axarr[0].set_title('Sharing X axis') axarr[1].scatter(x, y) # Two subplots, unpack the axes array immediately f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) ax1.plot(x, y) ax1.set_title('Sharing Y axis') ax2.scatter(x, y) # Three subplots sharing both x\/y axes f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True) ax1.plot(x, y) ax1.set_title('Sharing both axes') ax2.scatter(x, y) ax3.scatter(x, 2 * y ** 2 - 1, color='r') # Fine-tune figure; make subplots close to each other and hide x ticks for # all but bottom plot. f.subplots_adjust(hspace=0) plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) # row and column sharing f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') ax1.plot(x, y) ax1.set_title('Sharing x per column, y per row') ax2.scatter(x, y) ax3.scatter(x, 2 * y ** 2 - 1, color='r') ax4.plot(x, 2 * y ** 2 - 1, color='r') # Four axes, returned as a 2-d array f, axarr = plt.subplots(2, 2) axarr[0, 0].plot(x, y) axarr[0, 0].set_title('Axis [0,0]') axarr[0, 1].scatter(x, y) axarr[0, 1].set_title('Axis [0,1]') axarr[1, 0].plot(x, y ** 2) axarr[1, 0].set_title('Axis [1,0]') axarr[1, 1].scatter(x, y ** 2) axarr[1, 1].set_title('Axis [1,1]') # Fine-tune figure; hide x ticks for top plots and y ticks for right plots plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False) plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False) # Four polar axes f, axarr = plt.subplots(2, 2, subplot_kw=dict(projection='polar')) axarr[0, 0].plot(x, y) axarr[0, 0].set_title('Axis [0,0]') axarr[0, 1].scatter(x, y) axarr[0, 1].set_title('Axis [0,1]') axarr[1, 0].plot(x, y ** 2) axarr[1, 0].set_title('Axis [1,0]') axarr[1, 1].scatter(x, y ** 2) axarr[1, 1].set_title('Axis [1,1]') # Fine-tune figure; make subplots farther from each other. f.subplots_adjust(hspace=0.3) plt.show() ```",44 "response":"Use .set_figwidth and .set_figheight on the matplotlib.figure.Figure object returned by plt.subplots(), or set both with f.set_size_inches(w, h). ``` f.set_figheight(15) f.set_figwidth(15) ``` Note: Unlike set_size_inches(), where the measurement unit is explicitly mentioned in the function's name, this is not the case for set_figwidth() and set_figheight(), which also use inches. This information is provided by the documentation of the function. Alternatively, when using .subplots() to create a new figure, specify figsize=: ``` f, axs = plt.subplots(2, 2, figsize=(15, 15)) ``` .subplots accepts **fig_kw, which are passed to pyplot.figure, and is where figsize can be found. Setting the figure's size may trigger the ValueError exception: ``` Image size of 240000x180000 pixels is too large. It must be less than 2^16 in each direction ``` This is a common problem for using the set_fig*() functions due to the assumptions that they work with pixels and not inches (obviously 240000*180000 inches is too much).",45 "best_answers_score":0.8,46 "library_name":"matplotlib",47 "question_url":"https:\/\/stackoverflow.com\/questions\/14770735\/how-do-i-change-the-figure-size-with-subplots",48 "best_answers_votes":1222,49 "question_length":2402,50 "response_length":101851 },52 {53 "question":"What does the argument mean in fig.add_subplot(111)? Sometimes I come across code such as this: ``` import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] fig = plt.figure() fig.add_subplot(111) plt.scatter(x, y) plt.show() ``` Which produces: I've been reading the documentation like crazy but I can't find an explanation for the 111. sometimes I see a 212. What does the argument of fig.add_subplot() mean?",54 "response":"I think this would be best explained by the following picture: To initialize the above, one would type: ``` import matplotlib.pyplot as plt fig = plt.figure() fig.add_subplot(221) #top left fig.add_subplot(222) #top right fig.add_subplot(223) #bottom left fig.add_subplot(224) #bottom right plt.show() ```",55 "best_answers_score":0.8,56 "library_name":"matplotlib",57 "question_url":"https:\/\/stackoverflow.com\/questions\/3584805\/what-does-the-argument-mean-in-fig-add-subplot111",58 "best_answers_votes":638,59 "question_length":427,60 "response_length":30561 },62 {63 "question":"Hiding axis text in matplotlib plots I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis. This may be vague, but the following simplified example highlights the issue, with '6.18' being the offending value of N: ``` import matplotlib.pyplot as plt import random prefix = 6.18 rx = [prefix+(0.001*random.random()) for i in arange(100)] ry = [prefix+(0.001*random.random()) for i in arange(100)] plt.plot(rx,ry,'ko') frame1 = plt.gca() for xlabel_i in frame1.axes.get_xticklabels(): xlabel_i.set_visible(False) xlabel_i.set_fontsize(0.0) for xlabel_i in frame1.axes.get_yticklabels(): xlabel_i.set_fontsize(0.0) xlabel_i.set_visible(False) for tick in frame1.axes.get_xticklines(): tick.set_visible(False) for tick in frame1.axes.get_yticklines(): tick.set_visible(False) plt.show() ``` The three things I would like to know are: How to turn off this behaviour in the first place (although in most cases it is useful, it is not always!) I have looked through matplotlib.axis.XAxis and cannot find anything appropriate How can I make N disappear (i.e. X.set_visible(False)) Is there a better way to do the above anyway? My final plot would be 4x4 subplots in a figure, if that is relevant.",64 "response":"Instead of hiding each element, you can hide the whole axis: ``` frame1.axes.get_xaxis().set_visible(False) frame1.axes.get_yaxis().set_visible(False) ``` Or, you can set the ticks to an empty list: ``` frame1.axes.get_xaxis().set_ticks([]) frame1.axes.get_yaxis().set_ticks([]) ``` In this second option, you can still use plt.xlabel() and plt.ylabel() to add labels to the axes.",65 "best_answers_score":0.8,66 "library_name":"matplotlib",67 "question_url":"https:\/\/stackoverflow.com\/questions\/2176424\/hiding-axis-text-in-matplotlib-plots",68 "best_answers_votes":687,69 "question_length":1422,70 "response_length":38071 },72 {73 "question":"How to change the figure size of a seaborn axes or figure level plot How do I change the size of my image so it's suitable for printing? For example, I'd like to use an A4 paper, whose dimensions are 11.7 inches by 8.27 inches in landscape orientation.",74 "response":"You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set_theme method (which replaces the set method, deprecated in v0.11.0 (September 2020)) ``` import seaborn as sns sns.set_theme(rc={'figure.figsize':(11.7,8.27)}) ``` Other alternative may be to use figure.figsize of rcParams to set figure size as below: ``` from matplotlib import rcParams # figure size in inches rcParams['figure.figsize'] = 11.7,8.27 ``` More details can be found in matplotlib documentation",75 "best_answers_score":0.8,76 "library_name":"matplotlib",77 "question_url":"https:\/\/stackoverflow.com\/questions\/31594549\/how-to-change-the-figure-size-of-a-seaborn-axes-or-figure-level-plot",78 "best_answers_votes":568,79 "question_length":252,80 "response_length":51681 },82 {83 "question":"How to change tick label font size In a matplotlib figure, how can I make the font size for the tick labels using ax1.set_xticklabels() smaller? Further, how can one rotate it from horizontal to vertical?",84 "response":"There is a simpler way actually. I just found: ``` import matplotlib.pyplot as plt # We prepare the plot fig, ax = plt.subplots() # We change the fontsize of minor ticks label ax.tick_params(axis='both', which='major', labelsize=10) ax.tick_params(axis='both', which='minor', labelsize=8) ``` This only answers to the size of label part of your question though.",85 "best_answers_score":0.8,86 "library_name":"matplotlib",87 "question_url":"https:\/\/stackoverflow.com\/questions\/6390393\/how-to-change-tick-label-font-size",88 "best_answers_votes":844,89 "question_length":204,90 "response_length":36191 },92 {93 "question":"How to remove xticks from a plot I have a semilogx plot and I would like to remove the xticks. I tried: ``` plt.gca().set_xticks([]) plt.xticks([]) ax.set_xticks([]) ``` The grid disappears (ok), but small ticks (at the place of the main ticks) remain. How to remove them?",94 "response":"The plt.tick_params method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis. Note that there is also ax.tick_params for matplotlib.axes.Axes objects. ``` from matplotlib import pyplot as plt plt.plot(range(10)) plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off labelbottom=False) # labels along the bottom edge are off plt.show() plt.savefig('plot') plt.clf() ```",95 "best_answers_score":0.8,96 "library_name":"matplotlib",97 "question_url":"https:\/\/stackoverflow.com\/questions\/12998430\/how-to-remove-xticks-from-a-plot",98 "best_answers_votes":751,99 "question_length":272,100 "response_length":592101 },102 {103 "question":"Installation Issue with matplotlib Python [duplicate] This question already has answers here: python matplotlib framework under macosx? (11 answers) Closed 11 years ago. I have issue after installing the matplotlib package unable to import matplotlib.pyplot as plt. Any suggestion will be greatly appreciate. ``` >>> import matplotlib.pyplot as plt Traceback (most recent call last): File \"\", line 1, in File \"\/\/anaconda\/lib\/python2.7\/site-packages\/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg\/matplotlib\/pyplot.py\", line 98, in _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File \"\/\/anaconda\/lib\/python2.7\/site-packages\/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg\/matplotlib\/backends\/__init__.py\", line 28, in pylab_setup globals(),locals(),[backend_name],0) File \"\/\/anaconda\/lib\/python2.7\/site-packages\/matplotlib-1.3.1-py2.7-macosx-10.5-x86_64.egg\/matplotlib\/backends\/backend_macosx.py\", line 21, in from matplotlib.backends import _macosx **RuntimeError**: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. ```",104 "response":"Problem Cause In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os. Solution I assume you have installed the pip matplotlib, there is a directory in your root called ~\/.matplotlib. Create a file ~\/.matplotlib\/matplotlibrc there and add the following code: backend: TkAgg From this link you can try different diagrams.",105 "best_answers_score":0.8,106 "library_name":"matplotlib",107 "question_url":"https:\/\/stackoverflow.com\/questions\/21784641\/installation-issue-with-matplotlib-python",108 "best_answers_votes":1346,109 "question_length":1323,110 "response_length":525111 },112 {113 "question":"\"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.\" when plotting figure with pyplot on Pycharm I am trying to plot a simple graph using pyplot, e.g.: ``` import matplotlib.pyplot as plt plt.plot([1,2,3],[5,7,4]) plt.show() ``` but the figure does not appear and I get the following message: ``` UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. ``` I found and tried some advice to re-configure the \"backend\" mentioned in that warning, like so: ``` import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt ``` but this gives me an error message: ``` ModuleNotFoundError: No module named 'tkinter' ``` I assumed that I had to install this module separately, but pip install tkinter does not work: ``` Collecting tkinter Could not find a version that satisfies the requirement tkinter (from versions: ) No matching distribution found for tkinter ``` How can I make Matplotlib display the graph? See also: Why does tkinter (or turtle) seem to be missing or broken? Shouldn't it be part of the standard library? . This question is not a duplicate, because the answers discuss other backends besides the Tkinter one. Also see _tkinter.TclError: no display name and no $DISPLAY environment variable for issues with attempts to use Matplotlib remotely.",114 "response":"Solution 1: is to install the GUI backend tk I found a solution to my problem (thanks to the help of ImportanceOfBeingErnest). All I had to do was to install tkinter through the Linux bash terminal using the following command: ``` sudo apt-get install python3-tk ``` instead of installing it with pip or directly in the virtual environment in Pycharm. Solution 2: install any of the matplotlib supported GUI backends solution 1 works fine because you get a GUI backend... in this case the TkAgg however you can also fix the issue by installing any of the matplolib GUI backends like Qt5Agg, GTKAgg, Qt4Agg, etc for example pip install pyqt5 will fix the issue also NOTE: usually this error appears when you pip install matplotlib and you are trying to display a plot in a GUI window and you do not have a python module for GUI display. The authors of matplotlib made the pypi software deps not depend on any GUI backend because some people need matplotlib without any GUI backend.",115 "best_answers_score":0.8,116 "library_name":"matplotlib",117 "question_url":"https:\/\/stackoverflow.com\/questions\/56656777\/userwarning-matplotlib-is-currently-using-agg-which-is-a-non-gui-backend-so",118 "best_answers_votes":613,119 "question_length":1369,120 "response_length":980121 },122 {123 "question":"How to remove axis, legends, and white padding I would like to apply colormap to an image, and write the resulting image, without using axes, labels, titles, or anything automatically added by matplotlib. Here is what I did: ``` def make_image(inputname,outputname): data = mpimg.imread(inputname)[:,:,0] fig = plt.imshow(data) fig.set_cmap('hot') fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False) plt.savefig(outputname) ``` It successfully removes the axis of the figure, but the figure saved, presents a white padding, and a frame around the actual image. How can I remove them (at least the white padding)?",124 "response":"The axis('off') method resolves one of the problems more succinctly than separately changing each axis and border. It still leaves the white space around the border however. Adding bbox_inches='tight' to the savefig command almost gets you there; you can see in the example below that the white space left is much smaller, but still present. Newer versions of matplotlib may require bbox_inches=0 instead of the string 'tight' (via @episodeyang and @kadrach) ``` from numpy import random import matplotlib.pyplot as plt data = random.random((5,5)) img = plt.imshow(data, interpolation='nearest') img.set_cmap('hot') plt.axis('off') plt.savefig(\"test.png\", bbox_inches='tight') ```",125 "best_answers_score":0.8,126 "library_name":"matplotlib",127 "question_url":"https:\/\/stackoverflow.com\/questions\/9295026\/how-to-remove-axis-legends-and-white-padding",128 "best_answers_votes":660,129 "question_length":640,130 "response_length":680131 },132 {133 "question":"How to adjust padding with cutoff or overlapping labels Updated MRE with subplots I'm not sure of the usefulness of the original question and MRE. The margin padding seems to be properly adjusted for large x and y labels. The issue is reproducible with subplots. Using matplotlib 3.4.2 ```py fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6)) axes = axes.flatten() for ax in axes: ax.set_ylabel(r'$\\ln\\left(\\frac{x_a-x_b}{x_a-x_c}\\right)$') ax.set_xlabel(r'$\\ln\\left(\\frac{x_a-x_d}{x_a-x_e}\\right)$') plt.show() ``` Original I am plotting a dataset using matplotlib where I have an xlabel that is quite \"tall\" (it's a formula rendered in TeX that contains a fraction and is therefore has the height equivalent of a couple of lines of text). In any case, the bottom of the formula is always cut off when I draw the figures. Changing figure size doesn't seem to help this, and I haven't been able to figure out how to shift the x-axis \"up\" to make room for the xlabel. Something like that would be a reasonable temporary solution, but what would be nice would be to have a way to make matplotlib recognize automatically that the label is cut off and resize accordingly. Here's an example of what I mean: ``` import matplotlib.pyplot as plt plt.figure() plt.ylabel(r'$\\ln\\left(\\frac{x_a-x_b}{x_a-x_c}\\right)$') plt.xlabel(r'$\\ln\\left(\\frac{x_a-x_d}{x_a-x_e}\\right)$', fontsize=50) plt.title('Example with matplotlib 3.4.2\\nMRE no longer an issue') plt.show() ``` The entire ylabel is visible, however, the xlabel is cut off at the bottom. In the case this is a machine-specific problem, I am running this on OSX 10.6.8 with matplotlib 1.0.0",134 "response":"Use: ``` import matplotlib.pyplot as plt plt.gcf().subplots_adjust(bottom=0.15) # alternate option without .gcf plt.subplots_adjust(bottom=0.15) ``` to make room for the label, where plt.gcf() means get the current figure. plt.gca(), which gets the current Axes, can also be used. Edit: Since I gave the answer, matplotlib has added the plt.tight_layout() function. See matplotlib Tutorials: Tight Layout Guide So I suggest using it: ``` fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6)) axes = axes.flatten() for ax in axes: ax.set_ylabel(r'$\\ln\\left(\\frac{x_a-x_b}{x_a-x_c}\\right)$') ax.set_xlabel(r'$\\ln\\left(\\frac{x_a-x_d}{x_a-x_e}\\right)$') plt.tight_layout() plt.show() ```",135 "best_answers_score":0.8,136 "library_name":"matplotlib",137 "question_url":"https:\/\/stackoverflow.com\/questions\/6774086\/how-to-adjust-padding-with-cutoff-or-overlapping-labels",138 "best_answers_votes":686,139 "question_length":1645,140 "response_length":688141 },142 {143 "question":"Matplotlib different size subplots I need to add two subplots to a figure. One subplot needs to be about three times as wide as the second (same height). I accomplished this using GridSpec and the colspan argument but I would like to do this using figure so I can save to PDF. I can adjust the first figure using the figsize argument in the constructor, but how do I change the size of the second plot?",144 "response":"As of matplotlib 3.6.0, width_ratios and height_ratios can now be passed directly as keyword arguments to plt.subplots and subplot_mosaic, as per What's new in Matplotlib 3.6.0 (Sep 15, 2022). f, (a0, a1) = plt.subplots(1, 2, width_ratios=[3, 1]) f, (a0, a1, a2) = plt.subplots(3, 1, height_ratios=[1, 1, 3]) Another way is to use the subplots function and pass the width ratio with gridspec_kw matplotlib Tutorial: Customizing Figure Layouts Using GridSpec and Other Functions matplotlib.gridspec.GridSpec has available gridspect_kw options ```py import numpy as np import matplotlib.pyplot as plt # generate some data x = np.arange(0, 10, 0.2) y = np.sin(x) # plot it f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]}) a0.plot(x, y) a1.plot(y, x) f.tight_layout() f.savefig('grid_figure.pdf') ``` Because the question is canonical, here is an example with vertical subplots. ```py # plot it f, (a0, a1, a2) = plt.subplots(3, 1, gridspec_kw={'height_ratios': [1, 1, 3]}) a0.plot(x, y) a1.plot(x, y) a2.plot(x, y) f.tight_layout() ```",145 "best_answers_score":0.8,146 "library_name":"matplotlib",147 "question_url":"https:\/\/stackoverflow.com\/questions\/10388462\/matplotlib-different-size-subplots",148 "best_answers_votes":668,149 "question_length":402,150 "response_length":1054151 },152 {153 "question":"How to have one colorbar for all subplots I've spent entirely too long researching how to get two subplots to share the same y-axis with a single colorbar shared between the two in Matplotlib. What was happening was that when I called the colorbar() function in either subplot1 or subplot2, it would autoscale the plot such that the colorbar plus the plot would fit inside the 'subplot' bounding box, causing the two side-by-side plots to be two very different sizes. To get around this, I tried to create a third subplot which I then hacked to render no plot with just a colorbar present. The only problem is, now the heights and widths of the two plots are uneven, and I can't figure out how to make it look okay. Here is my code: ``` from __future__ import division import matplotlib.pyplot as plt import numpy as np from matplotlib import patches from matplotlib.ticker import NullFormatter # SIS Functions TE = 1 # Einstein radius g1 = lambda x,y: (TE\/2) * (y**2-x**2)\/((x**2+y**2)**(3\/2)) g2 = lambda x,y: -1*TE*x*y \/ ((x**2+y**2)**(3\/2)) kappa = lambda x,y: TE \/ (2*np.sqrt(x**2+y**2)) coords = np.linspace(-2,2,400) X,Y = np.meshgrid(coords,coords) g1out = g1(X,Y) g2out = g2(X,Y) kappaout = kappa(X,Y) for i in range(len(coords)): for j in range(len(coords)): if np.sqrt(coords[i]**2+coords[j]**2) <= TE: g1out[i][j]=0 g2out[i][j]=0 fig = plt.figure() fig.subplots_adjust(wspace=0,hspace=0) # subplot number 1 ax1 = fig.add_subplot(1,2,1,aspect='equal',xlim=[-2,2],ylim=[-2,2]) plt.title(r\"$\\gamma_{1}$\",fontsize=\"18\") plt.xlabel(r\"x ($\\theta_{E}$)\",fontsize=\"15\") plt.ylabel(r\"y ($\\theta_{E}$)\",rotation='horizontal',fontsize=\"15\") plt.xticks([-2.0,-1.5,-1.0,-0.5,0,0.5,1.0,1.5]) plt.xticks([-2.0,-1.5,-1.0,-0.5,0,0.5,1.0,1.5]) plt.imshow(g1out,extent=(-2,2,-2,2)) plt.axhline(y=0,linewidth=2,color='k',linestyle=\"--\") plt.axvline(x=0,linewidth=2,color='k',linestyle=\"--\") e1 = patches.Ellipse((0,0),2,2,color='white') ax1.add_patch(e1) # subplot number 2 ax2 = fig.add_subplot(1,2,2,sharey=ax1,xlim=[-2,2],ylim=[-2,2]) plt.title(r\"$\\gamma_{2}$\",fontsize=\"18\") plt.xlabel(r\"x ($\\theta_{E}$)\",fontsize=\"15\") ax2.yaxis.set_major_formatter( NullFormatter() ) plt.axhline(y=0,linewidth=2,color='k',linestyle=\"--\") plt.axvline(x=0,linewidth=2,color='k',linestyle=\"--\") plt.imshow(g2out,extent=(-2,2,-2,2)) e2 = patches.Ellipse((0,0),2,2,color='white') ax2.add_patch(e2) # subplot for colorbar ax3 = fig.add_subplot(1,1,1) ax3.axis('off') cbar = plt.colorbar(ax=ax2) plt.show() ```",154 "response":"Just place the colorbar in its own axis and use subplots_adjust to make room for it. As a quick example: ``` import numpy as np import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=2, ncols=2) for ax in axes.flat: im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1) fig.subplots_adjust(right=0.8) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(im, cax=cbar_ax) plt.show() ``` Note that the color range will be set by the last image plotted (that gave rise to im) even if the range of values is set by vmin and vmax. If another plot has, for example, a higher max value, points with higher values than the max of im will show in uniform color.",155 "best_answers_score":0.8,156 "library_name":"matplotlib",157 "question_url":"https:\/\/stackoverflow.com\/questions\/13784201\/how-to-have-one-colorbar-for-all-subplots",158 "best_answers_votes":445,159 "question_length":2485,160 "response_length":672161 },162 {163 "question":"Savefig outputs blank image I am trying to save plots I make using matplotlib; however, the images are saving blank. Here is my code: ``` plt.subplot(121) plt.imshow(dataStack, cmap=mpl.cm.bone) plt.subplot(122) y = copy.deepcopy(tumorStack) y = np.ma.masked_where(y == 0, y) plt.imshow(dataStack, cmap=mpl.cm.bone) plt.imshow(y, cmap=mpl.cm.jet_r, interpolation='nearest') if T0 is not None: plt.subplot(123) plt.imshow(T0, cmap=mpl.cm.bone) #plt.subplot(124) #Autozoom #else: #plt.subplot(124) #Autozoom plt.show() plt.draw() plt.savefig('tessstttyyy.png', dpi=100) ``` And tessstttyyy.png is blank (also tried with .jpg)",164 "response":"First, what happens when T0 is not None? I would test that, then I would adjust the values I pass to plt.subplot(); maybe try values 131, 132, and 133, or values that depend whether or not T0 exists. Second, after plt.show() is called, a new figure is created. To deal with this, you can Call plt.savefig('tessstttyyy.png', dpi=100) before you call plt.show() Save the figure before you show() by calling plt.gcf() for \"get current figure\", then you can call savefig() on this Figure object at any time. For example: ``` fig1 = plt.gcf() plt.show() plt.draw() fig1.savefig('tessstttyyy.png', dpi=100) ``` In your code, 'tesssttyyy.png' is blank because it is saving the new figure, to which nothing has been plotted.",165 "best_answers_score":0.8,166 "library_name":"matplotlib",167 "question_url":"https:\/\/stackoverflow.com\/questions\/9012487\/savefig-outputs-blank-image",168 "best_answers_votes":518,169 "question_length":623,170 "response_length":716171 },172 {173 "question":"How do I make a single legend for many subplots? I am plotting the same type of information, but for different countries, with multiple subplots with Matplotlib. That is, I have nine plots on a 3x3 grid, all with the same for lines (of course, different values per line). However, I have not figured out how to put a single legend (since all nine subplots have the same lines) on the figure just once. How do I do that?",174 "response":"There is also a nice function get_legend_handles_labels() you can call on the last axis (if you iterate over them) that would collect everything you need from label= arguments: ``` handles, labels = ax.get_legend_handles_labels() fig.legend(handles, labels, loc='upper center') ``` If the pyplot interface is being used instead of the Axes interface, use: ``` handles, labels = plt.gca().get_legend_handles_labels() ``` To remove legends from subplots, see Remove the legend on a matplotlib figure. To merge twinx legends, see Secondary axis with twinx(): how to add to legend.",175 "best_answers_score":0.8,176 "library_name":"matplotlib",177 "question_url":"https:\/\/stackoverflow.com\/questions\/9834452\/how-do-i-make-a-single-legend-for-many-subplots",178 "best_answers_votes":411,179 "question_length":419,180 "response_length":577181 },182 {183 "question":"Generating a PNG with matplotlib when DISPLAY is undefined I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing? ``` #!\/usr\/bin\/env python import networkx as nx import matplotlib import matplotlib.pyplot import matplotlib.pyplot as plt G=nx.Graph() G.add_node(1) G.add_nodes_from([2,3,4,5,6,7,8,9,10]) #nx.draw_graphviz(G) #nx_write_dot(G, 'node.png') nx.draw(G) plt.savefig(\"\/var\/www\/node.png\") Traceback (most recent call last): File \"graph.py\", line 13, in nx.draw(G) File \"\/usr\/lib\/pymodules\/python2.5\/networkx\/drawing\/nx_pylab.py\", line 124, in draw cf=pylab.gcf() File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/pyplot.py\", line 276, in gcf return figure() File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/pyplot.py\", line 254, in figure **kwargs) File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/backends\/backend_tkagg.py\", line 90, in new_figure_manager window = Tk.Tk() File \"\/usr\/lib\/python2.5\/lib-tk\/Tkinter.py\", line 1650, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable ``` I get a different error now: ``` #!\/usr\/bin\/env python import networkx as nx import matplotlib import matplotlib.pyplot import matplotlib.pyplot as plt matplotlib.use('Agg') G=nx.Graph() G.add_node(1) G.add_nodes_from([2,3,4,5,6,7,8,9,10]) #nx.draw_graphviz(G) #nx_write_dot(G, 'node.png') nx.draw(G) plt.savefig(\"\/var\/www\/node.png\") ``` ``` \/usr\/lib\/pymodules\/python2.5\/matplotlib\/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. if warn: warnings.warn(_use_error_msg) Traceback (most recent call last): File \"graph.py\", line 15, in nx.draw(G) File \"\/usr\/lib\/python2.5\/site-packages\/networkx-1.2.dev-py2.5.egg\/networkx\/drawing\/nx_pylab.py\", line 124, in draw cf=pylab.gcf() File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/pyplot.py\", line 276, in gcf return figure() File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/pyplot.py\", line 254, in figure **kwargs) File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/backends\/backend_tkagg.py\", line 90, in new_figure_manager window = Tk.Tk() File \"\/usr\/lib\/python2.5\/lib-tk\/Tkinter.py\", line 1650, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable ``` I get a different error now: ``` #!\/usr\/bin\/env python import networkx as nx import matplotlib import matplotlib.pyplot import matplotlib.pyplot as plt matplotlib.use('Agg') G=nx.Graph() G.add_node(1) G.add_nodes_from([2,3,4,5,6,7,8,9,10]) #nx.draw_graphviz(G) #nx_write_dot(G, 'node.png') nx.draw(G) plt.savefig(\"\/var\/www\/node.png\") ``` ``` \/usr\/lib\/pymodules\/python2.5\/matplotlib\/__init__.py:835: UserWarning: This call to matplotlib.use() has no effect because the the backend has already been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time. if warn: warnings.warn(_use_error_msg) Traceback (most recent call last): File \"graph.py\", line 15, in nx.draw(G) File \"\/usr\/lib\/python2.5\/site-packages\/networkx-1.2.dev-py2.5.egg\/networkx\/drawing\/nx_pylab.py\", line 124, in draw cf=pylab.gcf() File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/pyplot.py\", line 276, in gcf return figure() File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/pyplot.py\", line 254, in figure **kwargs) File \"\/usr\/lib\/pymodules\/python2.5\/matplotlib\/backends\/backend_tkagg.py\", line 90, in new_figure_manager window = Tk.Tk() File \"\/usr\/lib\/python2.5\/lib-tk\/Tkinter.py\", line 1650, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable ```",184 "response":"The main problem is that (on your system) matplotlib chooses an x-using backend by default. I just had the same problem on one of my servers. The solution for me was to add the following code in a place that gets read before any other pylab\/matplotlib\/pyplot import: ``` import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') ``` The alternative is to set it in your .matplotlibrc",185 "best_answers_score":0.8,186 "library_name":"matplotlib",187 "question_url":"https:\/\/stackoverflow.com\/questions\/2801882\/generating-a-png-with-matplotlib-when-display-is-undefined",188 "best_answers_votes":535,189 "question_length":4015,190 "response_length":417191 },192 {193 "question":"Display image as grayscale I'm trying to display a grayscale image using matplotlib.pyplot.imshow(). My problem is that the grayscale image is displayed as a colormap. I need it to be grayscale because I want to draw on top of the image with color. I read in the image and convert to grayscale using PIL's Image.open().convert(\"L\") ``` image = Image.open(file).convert(\"L\") ``` Then I convert the image to a matrix so that I can easily do some image processing using ``` matrix = scipy.misc.fromimage(image, 0) ``` However, when I do ``` figure() matplotlib.pyplot.imshow(matrix) show() ``` it displays the image using a colormap (i.e. it's not grayscale). What am I doing wrong here?",194 "response":"The following code will load an image from a file image.png and will display it as grayscale. ``` import numpy as np import matplotlib.pyplot as plt from PIL import Image fname = 'image.png' image = Image.open(fname).convert(\"L\") arr = np.asarray(image) plt.imshow(arr, cmap='gray', vmin=0, vmax=255) plt.show() ``` If you want to display the inverse grayscale, switch the cmap to cmap='gray_r'.",195 "best_answers_score":0.8,196 "library_name":"matplotlib",197 "question_url":"https:\/\/stackoverflow.com\/questions\/3823752\/display-image-as-grayscale",198 "best_answers_votes":520,199 "question_length":684,200 "response_length":395201 },202 {203 "question":"Modify tick label text I want to make some modifications to a few selected tick labels in a plot. For example, if I do: ``` label = axes.yaxis.get_major_ticks()[2].label label.set_fontsize(size) label.set_rotation('vertical') ``` the font size and the orientation of the tick label is changed. However, if try: ``` label.set_text('Foo') ``` the tick label is not modified. Also if I do: ``` print label.get_text() ``` nothing is printed. Here's some more strangeness. When I tried this: ```py import matplotlib.pyplot as plt import numpy as np axes = plt.figure().add_subplot(111) t = np.arange(0.0, 2.0, 0.01) s = np.sin(2*np.pi*t) axes.plot(t, s) for ticklabel in axes.get_xticklabels(): print(ticklabel.get_text()) ``` Only empty strings are printed, but the plot contains ticks labeled as '0.0', '0.5', '1.0', '1.5', and '2.0'.",204 "response":"Caveat: Unless the ticklabels are already set to a string (as is usually the case in e.g. a boxplot), this will not work with any version of matplotlib newer than 1.1.0. If you're working from the current github master, this won't work. I'm not sure what the problem is yet... It may be an unintended change, or it may not be... Normally, you'd do something along these lines: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() # We need to draw the canvas, otherwise the labels won't be positioned and # won't have values yet. fig.canvas.draw() labels = [item.get_text() for item in ax.get_xticklabels()] labels[1] = 'Testing' ax.set_xticklabels(labels) plt.show() ``` To understand the reason why you need to jump through so many hoops, you need to understand a bit more about how matplotlib is structured. Matplotlib deliberately avoids doing \"static\" positioning of ticks, etc, unless it's explicitly told to. The assumption is that you'll want to interact with the plot, and so the bounds of the plot, ticks, ticklabels, etc will be dynamically changing. Therefore, you can't just set the text of a given tick label. By default, it's re-set by the axis's Locator and Formatter every time the plot is drawn. However, if the Locators and Formatters are set to be static (FixedLocator and FixedFormatter, respectively), then the tick labels stay the same. This is what set_*ticklabels or ax.*axis.set_ticklabels does. Hopefully that makes it slighly more clear as to why changing an individual tick label is a bit convoluted. Often, what you actually want to do is just annotate a certain position. In that case, look into annotate, instead.",205 "best_answers_score":0.8,206 "library_name":"matplotlib",207 "question_url":"https:\/\/stackoverflow.com\/questions\/11244514\/modify-tick-label-text",208 "best_answers_votes":429,209 "question_length":831,210 "response_length":1653211 },212 {213 "question":"How can I convert an RGB image into grayscale in Python? I'm trying to use matplotlib to read in an RGB image and convert it to grayscale. In matlab I use this: ``` img = rgb2gray(imread('image.png')); ``` In the matplotlib tutorial they don't cover it. They just read in the image ``` import matplotlib.image as mpimg img = mpimg.imread('image.png') ``` and then they slice the array, but that's not the same thing as converting RGB to grayscale from what I understand. ``` lum_img = img[:,:,0] ``` I find it hard to believe that numpy or matplotlib doesn't have a built-in function to convert from rgb to gray. Isn't this a common operation in image processing? I wrote a very simple function that works with the image imported using imread in 5 minutes. It's horribly inefficient, but that's why I was hoping for a professional implementation built-in. Sebastian has improved my function, but I'm still hoping to find the built-in one. matlab's (NTSC\/PAL) implementation: ``` import numpy as np def rgb2gray(rgb): r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2] gray = 0.2989 * r + 0.5870 * g + 0.1140 * b return gray ```",214 "response":"How about doing it with Pillow: ``` from PIL import Image img = Image.open('image.png').convert('L') img.save('greyscale.png') ``` If an alpha (transparency) channel is present in the input image and should be preserved, use mode LA: ``` img = Image.open('image.png').convert('LA') ``` Using matplotlib and the formula ``` Y' = 0.2989 R + 0.5870 G + 0.1140 B ``` you could do: ``` import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140]) img = mpimg.imread('image.png') gray = rgb2gray(img) plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1) plt.show() ```",215 "best_answers_score":0.8,216 "library_name":"matplotlib",217 "question_url":"https:\/\/stackoverflow.com\/questions\/12201577\/how-can-i-convert-an-rgb-image-into-grayscale-in-python",218 "best_answers_votes":488,219 "question_length":1121,220 "response_length":664221 },222 {223 "question":"Is there a way to detach matplotlib plots so that the computation can continue? After these instructions in the Python interpreter one gets a window with a plot: ``` from matplotlib.pyplot import * plot([1,2,3]) show() # other code ``` Unfortunately, I don't know how to continue to interactively explore the figure created by show() while the program does further calculations. Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.",224 "response":"Use matplotlib's calls that won't block: Using draw(): ``` from matplotlib.pyplot import plot, draw, show plot([1,2,3]) draw() print('continue computation') # at the end call show to ensure window won't close. show() ``` Using interactive mode: ``` from matplotlib.pyplot import plot, ion, show ion() # enables interactive mode plot([1,2,3]) # result shows immediatelly (implicit draw()) print('continue computation') # at the end call show to ensure window won't close. show() ```",225 "best_answers_score":0.8,226 "library_name":"matplotlib",227 "question_url":"https:\/\/stackoverflow.com\/questions\/458209\/is-there-a-way-to-detach-matplotlib-plots-so-that-the-computation-can-continue",228 "best_answers_votes":265,229 "question_length":517,230 "response_length":481231 },232 {233 "question":"Rotate label text in seaborn I have a simple factorplot ``` import seaborn as sns g = sns.factorplot(\"name\", \"miss_ratio\", \"policy\", dodge=.2, linestyles=[\"none\", \"none\", \"none\", \"none\"], data=df[df[\"level\"] == 2]) ``` The problem is that the x labels all run together, making them unreadable. How do you rotate the text so that the labels are readable?",234 "response":"I had a problem with the answer by @mwaskorn, namely that ``` g.set_xticklabels(rotation=30) ``` fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add ``` plt.xticks(rotation=30) ```",235 "best_answers_score":0.8,236 "library_name":"matplotlib",237 "question_url":"https:\/\/stackoverflow.com\/questions\/26540035\/rotate-label-text-in-seaborn",238 "best_answers_votes":449,239 "question_length":353,240 "response_length":227241 },242 {243 "question":"Set markers for individual points on a line I have used Matplotlib to plot lines on a figure. Now I would now like to set the style, specifically the marker, for individual points on the line. How do I do this? To clarify my question, I want to be able to set the style for individual markers on a line, not every marker on said line.",244 "response":"Specify the keyword args linestyle and\/or marker in your call to plot. For example, using a dashed line and blue circle markers: ``` plt.plot(range(10), linestyle='--', marker='o', color='b', label='line with marker') plt.legend() ``` A shortcut call for the same thing: ``` plt.plot(range(10), '--bo', label='line with marker') plt.legend() ``` Here is a list of the possible line and marker styles: ``` ================ =============================== character description ================ =============================== - solid line style -- dashed line style -. dash-dot line style : dotted line style . point marker , pixel marker o circle marker v triangle_down marker ^ triangle_up marker triangle_right marker 1 tri_down marker 2 tri_up marker 3 tri_left marker 4 tri_right marker s square marker p pentagon marker * star marker h hexagon1 marker H hexagon2 marker + plus marker x x marker D diamond marker d thin_diamond marker | vline marker _ hline marker ================ =============================== ``` edit: with an example of marking an arbitrary subset of points, as requested in the comments: ``` import numpy as np import matplotlib.pyplot as plt xs = np.linspace(-np.pi, np.pi, 30) ys = np.sin(xs) markers_on = [12, 17, 18, 19] plt.plot(xs, ys, '-gD', markevery=markers_on, label='line with select markers') plt.legend() plt.show() ``` This last example using the markevery kwarg is possible in since 1.4+, due to the merge of this feature branch. If you are stuck on an older version of matplotlib, you can still achieve the result by overlaying a scatterplot on the line plot. See the edit history for more details.",245 "best_answers_score":0.8,246 "library_name":"matplotlib",247 "question_url":"https:\/\/stackoverflow.com\/questions\/8409095\/set-markers-for-individual-points-on-a-line",248 "best_answers_votes":552,249 "question_length":334,250 "response_length":1643251 },252 {253 "question":"Moving matplotlib legend outside of the axis makes it cutoff by the figure box I'm familiar with the following questions: Matplotlib savefig with a legend outside the plot How to put the legend out of the plot It seems that the answers in these questions have the luxury of being able to fiddle with the exact shrinking of the axis so that the legend fits. Shrinking the axes, however, is not an ideal solution because it makes the data smaller making it actually more difficult to interpret; particularly when its complex and there are lots of things going on ... hence needing a large legend The example of a complex legend in the documentation demonstrates the need for this because the legend in their plot actually completely obscures multiple data points. http:\/\/matplotlib.sourceforge.net\/users\/legend_guide.html#legend-of-complex-plots What I would like to be able to do is dynamically expand the size of the figure box to accommodate the expanding figure legend. ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(-2*np.pi, 2*np.pi, 0.1) fig = plt.figure(1) ax = fig.add_subplot(111) ax.plot(x, np.sin(x), label='Sine') ax.plot(x, np.cos(x), label='Cosine') ax.plot(x, np.arctan(x), label='Inverse tan') lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0)) ax.grid('on') ``` Notice how the final label 'Inverse tan' is actually outside the figure box (and looks badly cutoff - not publication quality!) Finally, I've been told that this is normal behaviour in R and LaTeX, so I'm a little confused why this is so difficult in python... Is there a historical reason? Is Matlab equally poor on this matter? I have the (only slightly) longer version of this code on pastebin http:\/\/pastebin.com\/grVjc007",254 "response":"[EDIT - 25th Feb 2025] My day job is no longer Python, so I'm not following the recent matplotlib developments. Please read all the newer answers here as there look to be some excellent modern suggestions compared to this solution from the ancient history of 2012. Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root). The code I am looking for is adjusting the savefig call to: ``` fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight') #Note that the bbox_extra_artists must be an iterable ``` This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired. ``` import matplotlib.pyplot as plt import numpy as np plt.gcf().clear() x = np.arange(-2*np.pi, 2*np.pi, 0.1) fig = plt.figure(1) ax = fig.add_subplot(111) ax.plot(x, np.sin(x), label='Sine') ax.plot(x, np.cos(x), label='Cosine') ax.plot(x, np.arctan(x), label='Inverse tan') handles, labels = ax.get_legend_handles_labels() lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1)) text = ax.text(-0.2,1.05, \"Aribitrary text\", transform=ax.transAxes) ax.set_title(\"Trigonometry\") ax.grid('on') fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight') ``` This produces: [edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm. [edit] Some of the comments below note that since 2019, the command has been simplified. plt.savefig('x.png', bbox_inches='tight') was sufficient. Thanks for sharing. \u2013 mateuszb Jun 27, 2019",255 "best_answers_score":0.8,256 "library_name":"matplotlib",257 "question_url":"https:\/\/stackoverflow.com\/questions\/10101700\/moving-matplotlib-legend-outside-of-the-axis-makes-it-cutoff-by-the-figure-box",258 "best_answers_votes":408,259 "question_length":1721,260 "response_length":2005261 },262 {263 "question":"How to convert a NumPy array to PIL image applying matplotlib colormap I want to take a NumPy 2D array which represents a grayscale image, and convert it to an RGB PIL image while applying some of the matplotlib colormaps. I can get a reasonable PNG output by using the pyplot.figure.figimage command: ``` dpi = 100.0 w, h = myarray.shape[1]\/dpi, myarray.shape[0]\/dpi fig = plt.figure(figsize=(w,h), dpi=dpi) fig.figimage(sub, cmap=cm.gist_earth) plt.savefig('out.png') ``` Although I could adapt this to get what I want (probably using StringIO do get the PIL image), I wonder if there is not a simpler way to do that, since it seems to be a very natural problem of image visualization. Let's say, something like this: ``` colored_PIL_image = magic_function(array, cmap) ```",264 "response":"Quite a busy one-liner, but here it is: First ensure your NumPy array, myarray, is normalised with the max value at 1.0. Apply the colormap directly to myarray. Rescale to the 0-255 range. Convert to integers, using np.uint8(). Use Image.fromarray(). And you're done: ``` from PIL import Image from matplotlib import cm im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255)) ``` with plt.savefig(): with im.save():",265 "best_answers_score":0.8,266 "library_name":"matplotlib",267 "question_url":"https:\/\/stackoverflow.com\/questions\/10965417\/how-to-convert-a-numpy-array-to-pil-image-applying-matplotlib-colormap",268 "best_answers_votes":400,269 "question_length":775,270 "response_length":418271 },272 {273 "question":"Reduce left and right margins in matplotlib plot I'm struggling to deal with my plot margins in matplotlib. I've used the code below to produce my chart: ``` plt.imshow(g) c = plt.colorbar() c.set_label(\"Number of Slabs\") plt.savefig(\"OutputToUse.png\") ``` However, I get an output figure with lots of white space on either side of the plot. I've searched google and read the matplotlib documentation, but I can't seem to find how to reduce this.",274 "response":"One way to automatically do this is the bbox_inches='tight' kwarg to plt.savefig. E.g. ``` import matplotlib.pyplot as plt import numpy as np data = np.arange(3000).reshape((100,30)) plt.imshow(data) plt.savefig('test.png', bbox_inches='tight') ``` Another way is to use fig.tight_layout() ``` import matplotlib.pyplot as plt import numpy as np xs = np.linspace(0, 1, 20); ys = np.sin(xs) fig = plt.figure() axes = fig.add_subplot(1,1,1) axes.plot(xs, ys) # This should be called after all axes have been added fig.tight_layout() fig.savefig('test.png') ```",275 "best_answers_score":0.8,276 "library_name":"matplotlib",277 "question_url":"https:\/\/stackoverflow.com\/questions\/4042192\/reduce-left-and-right-margins-in-matplotlib-plot",278 "best_answers_votes":392,279 "question_length":446,280 "response_length":557281 },282 {283 "question":"Getting individual colors from a color map in matplotlib If you have a Colormap cmap, for example: ``` cmap = matplotlib.cm.get_cmap('Spectral') ``` How can you get a particular colour out of it between 0 and 1, where 0 is the first colour in the map and 1 is the last colour in the map? Ideally, I would be able to get the middle colour in the map by doing: ``` >>> do_some_magic(cmap, 0.5) # Return an RGBA tuple (0.1, 0.2, 0.3, 1.0) ```",284 "response":"You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap object you have. ``` import matplotlib cmap = matplotlib.cm.get_cmap('Spectral') rgba = cmap(0.5) print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0) ``` For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with cmap.set_under() and cmap.set_over(). For \"special\" numbers such as np.nan and np.inf the default is to use the 0.0 value, this can be changed using cmap.set_bad() similarly to under and over as above. Finally it may be necessary for you to normalize your data such that it conforms to the range [0.0, 1.0]. This can be done using matplotlib.colors.Normalize simply as shown in the small example below where the arguments vmin and vmax describe what numbers should be mapped to 0.0 and 1.0 respectively. ``` import matplotlib norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0) print(norm(15.0)) # 0.5 ``` A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values. (Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)",285 "best_answers_score":0.8,286 "library_name":"matplotlib",287 "question_url":"https:\/\/stackoverflow.com\/questions\/25408393\/getting-individual-colors-from-a-color-map-in-matplotlib",288 "best_answers_votes":415,289 "question_length":439,290 "response_length":1367291 },292 {293 "question":"How to do a scatter plot with empty circles in Python? In Python, with Matplotlib, how can a scatter plot with empty circles be plotted? The goal is to draw empty circles around some of the colored disks already plotted by scatter(), so as to highlight them, ideally without having to redraw the colored circles. I tried facecolors=None, to no avail.",294 "response":"From the documentation for scatter: ``` Optional kwargs control the Collection properties; in particular: edgecolors: The string \u2018none\u2019 to plot faces with no outlines facecolors: The string \u2018none\u2019 to plot unfilled outlines ``` Try the following: ``` import matplotlib.pyplot as plt import numpy as np x = np.random.randn(60) y = np.random.randn(60) plt.scatter(x, y, s=80, facecolors='none', edgecolors='r') plt.show() ``` Note: For other types of plots see this post on the use of markeredgecolor and markerfacecolor.",295 "best_answers_score":0.8,296 "library_name":"matplotlib",297 "question_url":"https:\/\/stackoverflow.com\/questions\/4143502\/how-to-do-a-scatter-plot-with-empty-circles-in-python",298 "best_answers_votes":408,299 "question_length":350,300 "response_length":518301 },302 {303 "question":"ImportError: No module named matplotlib.pyplot [duplicate] This question already has answers here: ImportError: No module named requests (39 answers) Closed last year. I am currently practicing matplotlib. This is the first example I practice. ``` #!\/usr\/bin\/python import matplotlib.pyplot as plt radius = [1.0, 2.0, 3.0, 4.0] area = [3.14159, 12.56636, 28.27431, 50.26544] plt.plot(radius, area) plt.show() ``` When I run this script with python .\/plot_test.py, it shows plot correctly. However, I run it by itself, .\/plot_test.py, it throws the followings: ```none Traceback (most recent call last): File \".\/plot_test.py\", line 3, in import matplotlib.pyplot as plt ImportError: No module named matplotlib.pyplot ``` Does python look for matplotlib in different locations? The environment is: Mac OS X 10.8.4 64bit built-in python 2.7 numpy, scipy, matplotlib is installed with: ``` sudo port install py27-numpy py27-scipy py27-matplotlib \\ py27-ipython +notebook py27-pandas py27-sympy py27-nose ```",304 "response":"pip will make your life easy! Step 1: Install pip - Check if you have pip already simply by writing pip in the python console. If you don't have pip, get a python script called get-pip.py , via here: https:\/\/pip.pypa.io\/en\/latest\/installing.html or directly here: https:\/\/bootstrap.pypa.io\/get-pip.py (You may have to use Save As ..) Step 2: Take note of where the file got saved and cd the directory from command prompt. Run the get-pip.py script to install pip. You can write in cmd this line within quotes: \"python .\\get-pip.py\" Step 3: Now in cmd type: pip install matplotlib And you should be through.",305 "best_answers_score":0.8,306 "library_name":"matplotlib",307 "question_url":"https:\/\/stackoverflow.com\/questions\/18176591\/importerror-no-module-named-matplotlib-pyplot",308 "best_answers_votes":262,309 "question_length":1004,310 "response_length":606311 },312 {313 "question":"How to plot in multiple subplots I am a little confused about how this code works: ``` fig, axes = plt.subplots(nrows=2, ncols=2) plt.show() ``` How does the fig, axes work in this case? What does it do? Also why wouldn't this work to do the same thing: ``` fig = plt.figure() axes = fig.subplots(nrows=2, ncols=2) ```",314 "response":"There are several ways to do it. The subplots method creates the figure along with the subplots that are then stored in the ax array. For example: ``` import matplotlib.pyplot as plt x = range(10) y = range(10) fig, ax = plt.subplots(nrows=2, ncols=2) for row in ax: for col in row: col.plot(x, y) plt.show() ``` However, something like this will also work, it's not so \"clean\" though since you are creating a figure with subplots and then add on top of them: ``` fig = plt.figure() plt.subplot(2, 2, 1) plt.plot(x, y) plt.subplot(2, 2, 2) plt.plot(x, y) plt.subplot(2, 2, 3) plt.plot(x, y) plt.subplot(2, 2, 4) plt.plot(x, y) plt.show() ```",315 "best_answers_score":0.8,316 "library_name":"matplotlib",317 "question_url":"https:\/\/stackoverflow.com\/questions\/31726643\/how-to-plot-in-multiple-subplots",318 "best_answers_votes":343,319 "question_length":318,320 "response_length":641321 },322 {323 "question":"How to set xlim and ylim for a subplot [duplicate] This question already has answers here: How to set the subplot axis range (6 answers) Closed 10 years ago. I would like to limit the X and Y axis in matplotlib for a specific subplot. The subplot figure itself doesn't have any axis property. I want for example to change only the limits for the second plot: ``` import matplotlib.pyplot as plt fig=plt.subplot(131) plt.scatter([1,2],[3,4]) fig=plt.subplot(132) plt.scatter([10,20],[30,40]) fig=plt.subplot(133) plt.scatter([15,23],[35,43]) plt.show() ```",324 "response":"You should use the object-oriented interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*. plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc. ``` import matplotlib.pyplot as plt ax1 = plt.subplot(131) ax1.scatter([1, 2], [3, 4]) ax1.set_xlim([0, 5]) ax1.set_ylim([0, 5]) ax2 = plt.subplot(132) ax2.scatter([1, 2],[3, 4]) ax2.set_xlim([0, 5]) ax2.set_ylim([0, 5]) ``` and so on for as many axes as you want. Or better, wrap it all up in a loop: ``` import matplotlib.pyplot as plt DATA_x = ([1, 2], [2, 3], [3, 4]) DATA_y = DATA_x[::-1] XLIMS = [[0, 10]] * 3 YLIMS = [[0, 10]] * 3 for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)): ax = plt.subplot(1, 3, j + 1) ax.scatter(x, y) ax.set_xlim(xlim) ax.set_ylim(ylim) ```",325 "best_answers_score":0.8,326 "library_name":"matplotlib",327 "question_url":"https:\/\/stackoverflow.com\/questions\/15858192\/how-to-set-xlim-and-ylim-for-a-subplot",328 "best_answers_votes":370,329 "question_length":555,330 "response_length":912331 },332 {333 "question":"plot a circle with Matplotlib.pyplot surprisingly I didn't find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this: ``` import matplotlib.pyplot as plt circle=plt.Circle((0,0),2) # here must be something like circle.plot() or not? plt.show() ``` ... but still didn't get it working.",334 "response":"You need to add it to an axes. A Circle is a subclass of an Patch, and an axes has an add_patch method. (You can also use add_artist but it's not recommended.) Here's an example of doing this: ```py import matplotlib.pyplot as plt circle1 = plt.Circle((0, 0), 0.2, color='r') circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue') circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False) fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot # (or if you have an existing figure) # fig = plt.gcf() # ax = fig.gca() ax.add_patch(circle1) ax.add_patch(circle2) ax.add_patch(circle3) fig.savefig('plotcircles.png') ``` This results in the following figure: The first circle is at the origin, but by default clip_on is True, so the circle is clipped when ever it extends beyond the axes. The third (green) circle shows what happens when you don't clip the Artist. It extends beyond the axes (but not beyond the figure, ie the figure size is not automatically adjusted to plot all of your artists). The units for x, y and radius correspond to data units by default. In this case, I didn't plot anything on my axes (fig.gca() returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1. Here's a continuation of the example, showing how units matter: ```py circle1 = plt.Circle((0, 0), 2, color='r') # now make a circle with no fill, which is good for hi-lighting key results circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False) circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False) ax = plt.gca() ax.cla() # clear things for fresh plot # change default range so that new circles will work ax.set_xlim((0, 10)) ax.set_ylim((0, 10)) # some data ax.plot(range(11), 'o', color='black') # key data point that we are encircling ax.plot((5), (5), 'o', color='y') ax.add_patch(circle1) ax.add_patch(circle2) ax.add_patch(circle3) fig.savefig('plotcircles2.png') ``` which results in: You can see how I set the fill of the 2nd circle to False, which is useful for encircling key results (like my yellow data point).",335 "best_answers_score":0.8,336 "library_name":"matplotlib",337 "question_url":"https:\/\/stackoverflow.com\/questions\/9215658\/plot-a-circle-with-matplotlib-pyplot",338 "best_answers_votes":348,339 "question_length":400,340 "response_length":2086341 },342 {343 "question":"Specifying and saving a figure with exact size in pixels Say I have an image of size 3841 x 7195 pixels. I would like to save the contents of the figure to disk, resulting in an image of the exact size I specify in pixels. No axis, no titles. Just the image. I don't personally care about DPIs, as I only want to specify the size the image takes in the screen in disk in pixels. I have read other threads, and they all seem to do conversions to inches and then specify the dimensions of the figure in inches and adjust dpi's in some way. I would like to avoid dealing with the potential loss of accuracy that could result from pixel-to-inches conversions. I have tried with: ``` w = 7195 h = 3841 fig = plt.figure(frameon=False) fig.set_size_inches(w,h) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(im_np, aspect='normal') fig.savefig(some_path, dpi=1) ``` with no luck (Python complains that width and height must each be below 32768 (?)) From everything I have seen, matplotlib requires the figure size to be specified in inches and dpi, but I am only interested in the pixels the figure takes in disk. How can I do this? To clarify: I am looking for a way to do this with matplotlib, and not with other image-saving libraries.",344 "response":"Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example this link will detect that for you. If you have an image of 3841x7195 pixels it is unlikely that you monitor will be that large, so you won't be able to show a figure of that size (matplotlib requires the figure to fit in the screen, if you ask for a size too large it will shrink to the screen size). Let's imagine you want an 800x800 pixel image just for an example. Here's how to show an 800x800 pixel image in my monitor (my_dpi=96): ``` plt.figure(figsize=(800\/my_dpi, 800\/my_dpi), dpi=my_dpi) ``` So you basically just divide the dimensions in pixels by your DPI. If you want to save a figure of a specific size, then it is a different matter. Screen DPIs are not so important anymore (unless you ask for a figure that won't fit in the screen). Using the same example of the 800x800 pixel figure, we can save it in different resolutions using the dpi keyword of savefig. To save it in the same resolution as the screen just use the same dpi: ``` plt.savefig('my_fig.png', dpi=my_dpi) ``` To save it as an 8000x8000 pixel image, use a dpi 10 times larger: ``` plt.savefig('my_fig.png', dpi=my_dpi * 10) ``` Note that the setting of the DPI is not supported by all backends. Here, the PNG backend is used, but the pdf and ps backends will implement the size differently. Also, changing the DPI and sizes will also affect things like fontsize. A larger DPI will keep the same relative sizes of fonts and elements, but if you want smaller fonts for a larger figure you need to increase the physical size instead of the DPI. Getting back to your example, if you want to save a image with 3841 x 7195 pixels, you could do the following: ``` plt.figure(figsize=(3.841, 7.195), dpi=100) ( your code ...) plt.savefig('myfig.png', dpi=1000) ``` Note that I used the figure dpi of 100 to fit in most screens, but saved with dpi=1000 to achieve the required resolution. In my system this produces a png with 3840x7190 pixels -- it seems that the DPI saved is always 0.02 pixels\/inch smaller than the selected value, which will have a (small) effect on large image sizes. Some more discussion of this here.",345 "best_answers_score":0.8,346 "library_name":"matplotlib",347 "question_url":"https:\/\/stackoverflow.com\/questions\/13714454\/specifying-and-saving-a-figure-with-exact-size-in-pixels",348 "best_answers_votes":277,349 "question_length":1266,350 "response_length":2293351 },352 {353 "question":"Date ticks and rotation [duplicate] This question already has answers here: Rotate axis tick labels (13 answers) Closed 2 years ago. I am having an issue trying to get my date ticks rotated in matplotlib. A small sample program is below. If I try to rotate the ticks at the end, the ticks do not get rotated. If I try to rotate the ticks as shown under the comment 'crashes', then matplot lib crashes. This only happens if the x-values are dates. If I replaces the variable dates with the variable t in the call to avail_plot, the xticks(rotation=70) call works just fine inside avail_plot. Any ideas? ``` import numpy as np import matplotlib.pyplot as plt import datetime as dt def avail_plot(ax, x, y, label, lcolor): ax.plot(x,y,'b') ax.set_ylabel(label, rotation='horizontal', color=lcolor) ax.get_yaxis().set_ticks([]) #crashes #plt.xticks(rotation=70) ax2 = ax.twinx() ax2.plot(x, [1 for a in y], 'b') ax2.get_yaxis().set_ticks([]) ax2.set_ylabel('testing') f, axs = plt.subplots(2, sharex=True, sharey=True) t = np.arange(0.01, 5, 1) s1 = np.exp(t) start = dt.datetime.now() dates=[] for val in t: next_val = start + dt.timedelta(0,val) dates.append(next_val) start = next_val avail_plot(axs[0], dates, s1, 'testing', 'green') avail_plot(axs[1], dates, s1, 'testing2', 'red') plt.subplots_adjust(hspace=0, bottom=0.3) plt.yticks([0.5,],(\"\",\"\")) #doesn't crash, but does not rotate the xticks #plt.xticks(rotation=70) plt.show() ```",354 "response":"If you prefer a non-object-oriented approach, move plt.xticks(rotation=70) to right before the two avail_plot calls, eg ``` plt.xticks(rotation=70) avail_plot(axs[0], dates, s1, 'testing', 'green') avail_plot(axs[1], dates, s1, 'testing2', 'red') ``` This sets the rotation property before setting up the labels. Since you have two axes here, plt.xticks gets confused after you've made the two plots. At the point when plt.xticks doesn't do anything, plt.gca() does not give you the axes you want to modify, and so plt.xticks, which acts on the current axes, is not going to work. For an object-oriented approach not using plt.xticks, you can use ``` plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 ) ``` after the two avail_plot calls. This sets the rotation on the correct axes specifically.",355 "best_answers_score":0.8,356 "library_name":"matplotlib",357 "question_url":"https:\/\/stackoverflow.com\/questions\/11264521\/date-ticks-and-rotation",358 "best_answers_votes":319,359 "question_length":1438,360 "response_length":803361 },362 {363 "question":"How to add hovering annotations to a plot I am using matplotlib to make scatter plots. Each point on the scatter plot is associated with a named object. I would like to be able to see the name of an object when I hover my cursor over the point on the scatter plot associated with that object. In particular, it would be nice to be able to quickly see the names of the points that are outliers. The closest thing I have been able to find while searching here is the annotate command, but that appears to create a fixed label on the plot. Unfortunately, with the number of points that I have, the scatter plot would be unreadable if I labeled each point. Does anyone know of a way to create labels that only appear when the cursor hovers in the vicinity of that point?",364 "response":"Here is a code that uses a scatter and shows an annotation upon hovering over the scatter points. ``` import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) x = np.random.rand(15) y = np.random.rand(15) names = np.array(list(\"ABCDEFGHIJKLMNO\")) c = np.random.randint(1,5,size=15) norm = plt.Normalize(1,4) cmap = plt.cm.RdYlGn fig,ax = plt.subplots() sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm) annot = ax.annotate(\"\", xy=(0,0), xytext=(20,20),textcoords=\"offset points\", bbox=dict(boxstyle=\"round\", fc=\"w\"), arrowprops=dict(arrowstyle=\"->\")) annot.set_visible(False) def update_annot(ind): pos = sc.get_offsets()[ind[\"ind\"][0]] annot.xy = pos text = \"{}, {}\".format(\" \".join(list(map(str,ind[\"ind\"]))), \" \".join([names[n] for n in ind[\"ind\"]])) annot.set_text(text) annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind[\"ind\"][0]]))) annot.get_bbox_patch().set_alpha(0.4) def hover(event): vis = annot.get_visible() if event.inaxes == ax: cont, ind = sc.contains(event) if cont: update_annot(ind) annot.set_visible(True) fig.canvas.draw_idle() else: if vis: annot.set_visible(False) fig.canvas.draw_idle() fig.canvas.mpl_connect(\"motion_notify_event\", hover) plt.show() ``` Because people also want to use this solution for a line plot instead of a scatter, the following would be the same solution for plot (which works slightly differently). ```css import matplotlib.pyplot as plt import numpy as np; np.random.seed(1) x = np.sort(np.random.rand(15)) y = np.sort(np.random.rand(15)) names = np.array(list(\"ABCDEFGHIJKLMNO\")) norm = plt.Normalize(1,4) cmap = plt.cm.RdYlGn fig,ax = plt.subplots() line, = plt.plot(x,y, marker=\"o\") annot = ax.annotate(\"\", xy=(0,0), xytext=(-20,20),textcoords=\"offset points\", bbox=dict(boxstyle=\"round\", fc=\"w\"), arrowprops=dict(arrowstyle=\"->\")) annot.set_visible(False) def update_annot(ind): x,y = line.get_data() annot.xy = (x[ind[\"ind\"][0]], y[ind[\"ind\"][0]]) text = \"{}, {}\".format(\" \".join(list(map(str,ind[\"ind\"]))), \" \".join([names[n] for n in ind[\"ind\"]])) annot.set_text(text) annot.get_bbox_patch().set_alpha(0.4) def hover(event): vis = annot.get_visible() if event.inaxes == ax: cont, ind = line.contains(event) if cont: update_annot(ind) annot.set_visible(True) fig.canvas.draw_idle() else: if vis: annot.set_visible(False) fig.canvas.draw_idle() fig.canvas.mpl_connect(\"motion_notify_event\", hover) plt.show() ``` In case someone is looking for a solution for lines in twin axes, refer to How to make labels appear when hovering over a point in multiple axis? In case someone is looking for a solution for bar plots, please refer to e.g. this answer.",365 "best_answers_score":0.8,366 "library_name":"matplotlib",367 "question_url":"https:\/\/stackoverflow.com\/questions\/7908636\/how-to-add-hovering-annotations-to-a-plot",368 "best_answers_votes":259,369 "question_length":766,370 "response_length":2626371 },372 {373 "question":"Format y axis as percent I have an existing plot that was created with pandas like this: ``` df['myvar'].plot(kind='bar') ``` The y axis is format as float and I want to change the y axis to percentages. All of the solutions I found use ax.xyz syntax and I can only place code below the line above that creates the plot (I cannot add ax=ax to the line above.) How can I format the y axis as percentages without changing the line above? Here is the solution I found but requires that I redefine the plot: ``` import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as mtick data = [8,12,15,17,18,18.5] perc = np.linspace(0,100,len(data)) fig = plt.figure(1, (7,4)) ax = fig.add_subplot(1,1,1) ax.plot(perc, data) fmt = '%.0f%%' # Format you want the ticks, e.g. '40%' xticks = mtick.FormatStrFormatter(fmt) ax.xaxis.set_major_formatter(xticks) plt.show() ``` Link to the above solution: Pyplot: using percentage on x axis",374 "response":"This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker): ``` import ... import matplotlib.ticker as mtick ax = df['myvar'].plot(kind='bar') ax.yaxis.set_major_formatter(mtick.PercentFormatter()) ``` PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0). The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None and '%', respectively. decimals=None will automatically set the number of decimal points based on how much of the axes you are showing. Update PercentFormatter was introduced into Matplotlib proper in version 2.1.0.",375 "best_answers_score":0.8,376 "library_name":"matplotlib",377 "question_url":"https:\/\/stackoverflow.com\/questions\/31357611\/format-y-axis-as-percent",378 "best_answers_votes":376,379 "question_length":940,380 "response_length":961381 },382 {383 "question":"reducing number of plot ticks I have too many ticks on my graph and they are running into each other. How can I reduce the number of ticks? For example, I have ticks: ``` 1E-6, 1E-5, 1E-4, ... 1E6, 1E7 ``` And I only want: ``` 1E-5, 1E-3, ... 1E5, 1E7 ``` I've tried playing with the LogLocator, but I haven't been able to figure this out.",384 "response":"Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator), there is pyplot.locator_params, ``` pyplot.locator_params(nbins=4) ``` You can specify specific axis in this method as mentioned below, default is both: ``` # To specify the number of ticks on both or any single axes pyplot.locator_params(axis='y', nbins=6) pyplot.locator_params(axis='x', nbins=10) ```",385 "best_answers_score":0.8,386 "library_name":"matplotlib",387 "question_url":"https:\/\/stackoverflow.com\/questions\/6682784\/reducing-number-of-plot-ticks",388 "best_answers_votes":368,389 "question_length":339,390 "response_length":442391 },392 {393 "question":"_tkinter.TclError: no display name and no $DISPLAY environment variable I am running a simple python script in the server: ``` import matplotlib.pyplot as plt import numpy as np x = np.random.randn(60) y = np.random.randn(60) plt.scatter(x, y, s=20) out_png = 'path\/to\/store\/out_file.png' plt.savefig(out_png, dpi=150) ``` I try to use the command python example.py in this server which has matplotlib 1.5.1 installed it fails with the error: ``` Traceback (most recent call last): File \"example.py\", line 7, in plt.scatter(x, y, s=20) File \"\/home\/USER\/.virtualenvs\/nnet\/lib\/python2.7\/site-packages\/matplotlib\/pyplot.py\", line 3241, in scatter ax = gca() File \"\/home\/USER\/.virtualenvs\/nnet\/lib\/python2.7\/site-packages\/matplotlib\/pyplot.py\", line 928, in gca return gcf().gca(**kwargs) File \"\/home\/USER\/.virtualenvs\/nnet\/lib\/python2.7\/site-packages\/matplotlib\/pyplot.py\", line 578, in gcf return figure() File \"\/home\/USER\/.virtualenvs\/nnet\/lib\/python2.7\/site-packages\/matplotlib\/pyplot.py\", line 527, in figure **kwargs) File \"\/home\/USER\/.virtualenvs\/nnet\/lib\/python2.7\/site-packages\/matplotlib\/backends\/backend_tkagg.py\", line 84, in new_figure_manager return new_figure_manager_given_figure(num, figure) File \"\/home\/USER\/.virtualenvs\/nnet\/lib\/python2.7\/site-packages\/matplotlib\/backends\/backend_tkagg.py\", line 92, in new_figure_manager_given_figure window = Tk.Tk() File \"\/usr\/local\/lib\/python2.7\/lib-tk\/Tkinter.py\", line 1810, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable ``` What is happening here?",394 "response":"Matplotlib chooses Xwindows backend by default. You need to set matplotlib to not use the Xwindows backend. Add this code to the start of your script (before importing pyplot) and try again: ``` import matplotlib matplotlib.use('Agg') ``` Or add to .config\/matplotlib\/matplotlibrc line backend: Agg to use non-interactive backend. ```sh echo \"backend: Agg\" > ~\/.config\/matplotlib\/matplotlibrc ``` Or when connect to server use ssh -X remoteMachine command to use Xwindows. Also you may try to export display: export DISPLAY=mymachine.com:0.0. For more info: https:\/\/matplotlib.org\/faq\/howto_faq.html#matplotlib-in-a-web-application-server",395 "best_answers_score":0.8,396 "library_name":"matplotlib",397 "question_url":"https:\/\/stackoverflow.com\/questions\/37604289\/tkinter-tclerror-no-display-name-and-no-display-environment-variable",398 "best_answers_votes":348,399 "question_length":1645,400 "response_length":638401 },402 {403 "question":"Plotting in a non-blocking way with Matplotlib I am having problems trying to make matplotlib plot a function without blocking execution. I have tried using show(block=False) as some people suggest, but all I get is a frozen window. If I simply call show(), the result is plotted properly but execution is blocked until the window is closed. From other threads I've read, I suspect that whether show(block=False) works or not depends on the backend. Is this correct? My backend is Qt4Agg. Could you have a look at my code and tell me if you see something wrong? Here is my code. ``` from math import * from matplotlib import pyplot as plt print(plt.get_backend()) def main(): x = range(-50, 51, 1) for pow in range(1,5): # plot x^1, x^2, ..., x^4 y = [Xi**pow for Xi in x] print(y) plt.plot(x, y) plt.draw() #plt.show() #this plots correctly, but blocks execution. plt.show(block=False) #this creates an empty frozen window. _ = raw_input(\"Press [enter] to continue.\") if __name__ == '__main__': main() ``` PS. I forgot to say that I would like to update the existing window every time I plot something, instead of creating a new one.",404 "response":"I spent a long time looking for solutions, and found this answer. It looks like, in order to get what you (and I) want, you need the combination of plt.ion(), plt.show() (not with block=False) and, most importantly, plt.pause(.001) (or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that\u2014I don't know. Here's an implementation that works for me on python 3.5: ``` import numpy as np from matplotlib import pyplot as plt def main(): plt.axis([-50,50,0,10000]) plt.ion() plt.show() x = np.arange(-50, 51) for pow in range(1,5): # plot x^1, x^2, ..., x^4 y = [Xi**pow for Xi in x] plt.plot(x, y) plt.draw() plt.pause(0.001) input(\"Press [enter] to continue.\") if __name__ == '__main__': main() ```",405 "best_answers_score":0.8,406 "library_name":"matplotlib",407 "question_url":"https:\/\/stackoverflow.com\/questions\/28269157\/plotting-in-a-non-blocking-way-with-matplotlib",408 "best_answers_votes":262,409 "question_length":1134,410 "response_length":880411 },412 {413 "question":"How to plot multiple dataframes in subplots I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking df.plot(), I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately failing to come up with a solution to how and would highly appreciate some help.",414 "response":"You can manually create the subplots with matplotlib, and then plot the dataframes on a specific subplot using the ax keyword. For example for 4 subplots (2x2): ``` import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=2, ncols=2) df1.plot(ax=axes[0,0]) df2.plot(ax=axes[0,1]) ... ``` Here axes is an array which holds the different subplot axes, and you can access one just by indexing axes. If you want a shared x-axis, then you can provide sharex=True to plt.subplots.",415 "best_answers_score":0.8,416 "library_name":"matplotlib",417 "question_url":"https:\/\/stackoverflow.com\/questions\/22483588\/how-to-plot-multiple-dataframes-in-subplots",418 "best_answers_votes":414,419 "question_length":371,420 "response_length":480421 },422 {423 "question":"How do I equalize the scales of the x-axis and y-axis? How do I create a plot where the scales of x-axis and y-axis are the same? This equal ratio should be maintained even if I change the window size. Currently, my graph scales together with the window size. I tried: ``` plt.xlim(-3, 3) plt.ylim(-3, 3) plt.axis('equal') ```",424 "response":"Use Axes.set_aspect in the following manner: ``` from matplotlib import pyplot as plt plt.plot(range(5)) plt.xlim(-3, 3) plt.ylim(-3, 3) ax = plt.gca() ax.set_aspect('equal', adjustable='box') plt.draw() ```",425 "best_answers_score":0.8,426 "library_name":"matplotlib",427 "question_url":"https:\/\/stackoverflow.com\/questions\/17990845\/how-do-i-equalize-the-scales-of-the-x-axis-and-y-axis",428 "best_answers_votes":323,429 "question_length":326,430 "response_length":207431 },432 {433 "question":"matplotlib error - no module named tkinter [duplicate] This question already has answers here: \"UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.\" when plotting figure with pyplot on Pycharm (31 answers) Closed 2 years ago. I tried to use the matplotlib package via Pycharm IDE on windows 10. when I run this code: ``` from matplotlib import pyplot ``` I get the following error: ``` ImportError: No module named 'tkinter' ``` I know that in python 2.x it was called Tkinter, but that is not the problem - I just installed a brand new python 3.5.1. EDIT: in addition, I also tried to import 'tkinter' and 'Tkinter' - neither of these worked (both returned the error message I mentioned).",434 "response":"For Linux Debian based distros: ``` sudo apt-get install python3-tk ``` RPM based distros: ``` sudo yum install python3-tkinter ``` For windows: For Windows, I think the problem is you didn't install complete Python package. Since Tkinter should be shipped with Python out of box. See: http:\/\/www.tkdocs.com\/tutorial\/install.html . Good python distributions for Windows can be found by the companies Anaconda or ActiveState. Test the python module ``` python -c \"import tkinter\" ``` p.s. I suggest installing ipython, which provides powerful shell and necessary packages as well.",435 "best_answers_score":0.8,436 "library_name":"matplotlib",437 "question_url":"https:\/\/stackoverflow.com\/questions\/36327134\/matplotlib-error-no-module-named-tkinter",438 "best_answers_votes":255,439 "question_length":740,440 "response_length":579441 },442 {443 "question":"How to update a plot in matplotlib I'm having issues with redrawing the figure here. I allow the user to specify the units in the time scale (x-axis) and then I recalculate and call this function plots(). I want the plot to simply update, not append another plot to the figure. ``` def plots(): global vlgaBuffSorted cntr() result = collections.defaultdict(list) for d in vlgaBuffSorted: result[d['event']].append(d) result_list = result.values() f = Figure() graph1 = f.add_subplot(211) graph2 = f.add_subplot(212,sharex=graph1) for item in result_list: tL = [] vgsL = [] vdsL = [] isubL = [] for dict in item: tL.append(dict['time']) vgsL.append(dict['vgs']) vdsL.append(dict['vds']) isubL.append(dict['isub']) graph1.plot(tL,vdsL,'bo',label='a') graph1.plot(tL,vgsL,'rp',label='b') graph2.plot(tL,isubL,'b-',label='c') plotCanvas = FigureCanvasTkAgg(f, pltFrame) toolbar = NavigationToolbar2TkAgg(plotCanvas, pltFrame) toolbar.pack(side=BOTTOM) plotCanvas.get_tk_widget().pack(side=TOP) ```",444 "response":"You essentially have two options: Do exactly what you're currently doing, but call graph1.clear() and graph2.clear() before replotting the data. This is the slowest, but most simplest and most robust option. Instead of replotting, you can just update the data of the plot objects. You'll need to make some changes in your code, but this should be much, much faster than replotting things every time. However, the shape of the data that you're plotting can't change, and if the range of your data is changing, you'll need to manually reset the x and y axis limits. To give an example of the second option: ``` import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 6*np.pi, 100) y = np.sin(x) # You probably won't need this if you're embedding things in a tkinter plot... plt.ion() fig = plt.figure() ax = fig.add_subplot(111) line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma for phase in np.linspace(0, 10*np.pi, 500): line1.set_ydata(np.sin(x + phase)) fig.canvas.draw() fig.canvas.flush_events() ```",445 "best_answers_score":0.8,446 "library_name":"matplotlib",447 "question_url":"https:\/\/stackoverflow.com\/questions\/4098131\/how-to-update-a-plot-in-matplotlib",448 "best_answers_votes":258,449 "question_length":993,450 "response_length":1046451 },452 {453 "question":"Set Colorbar Range I have the following code: ```py import matplotlib.pyplot as plt cdict = { 'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)), 'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)), 'blue' : ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45)) } cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024) plt.clf() plt.pcolor(X, Y, v, cmap=cm) plt.loglog() plt.xlabel('X Axis') plt.ylabel('Y Axis') plt.colorbar() plt.show() ``` This produces a graph of the values v on the axes X vs Y, using the specified colormap. The X and Y axes are perfect, but the colormap spreads between the min and max of v. I would like to force the colormap to range between 0 and 1. I thought of using: ```py plt.axis(...) ``` To set the ranges of the axes, but this only takes arguments for the min and max of X and Y, not the colormap. Edit: For clarity, let's say I have one graph whose values range (0 ... 0.3), and another graph whose values (0.2 ... 0.8). In both graphs, I will want the range of the colorbar to be (0 ... 1). In both graphs, I want this range of colour to be identical using the full range of cdict above (so 0.25 in both graphs will be the same colour). In the first graph, all colours between 0.3 and 1.0 won't feature in the graph, but will in the colourbar key at the side. In the other, all colours between 0 and 0.2, and between 0.8 and 1 will not feature in the graph, but will in the colourbar at the side.",454 "response":"Using vmin and vmax forces the range for the colors. Here's an example: ``` import matplotlib as m import matplotlib.pyplot as plt import numpy as np cdict = { 'red' : ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)), 'green': ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)), 'blue' : ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45)) } cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024) x = np.arange(0, 10, .1) y = np.arange(0, 10, .1) X, Y = np.meshgrid(x,y) data = 2*( np.sin(X) + np.sin(3*Y) ) def do_plot(n, f, title): #plt.clf() plt.subplot(1, 3, n) plt.pcolor(X, Y, f(data), cmap=cm, vmin=-4, vmax=4) plt.title(title) plt.colorbar() plt.figure() do_plot(1, lambda x:x, \"all\") do_plot(2, lambda x:np.clip(x, -4, 0), \"0\") plt.show() ```",455 "best_answers_score":0.8,456 "library_name":"matplotlib",457 "question_url":"https:\/\/stackoverflow.com\/questions\/3373256\/set-colorbar-range",458 "best_answers_votes":242,459 "question_length":1463,460 "response_length":770461 },462 {463 "question":"How to put individual tags for a matplotlib scatter plot? I am trying to do a scatter plot in matplotlib and I couldn't find a way to add tags to the points. For example: ``` scatter1=plt.scatter(data1[\"x\"], data1[\"y\"], marker=\"o\", c=\"blue\", facecolors=\"white\", edgecolors=\"blue\") ``` I want for the points in \"y\" to have labels as \"point 1\", \"point 2\", etc. I couldn't figure it out.",464 "response":"Perhaps use plt.annotate: ``` import numpy as np import matplotlib.pyplot as plt N = 10 data = np.random.random((N, 4)) labels = ['point{0}'.format(i) for i in range(N)] plt.subplots_adjust(bottom = 0.1) plt.scatter( data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500, cmap=plt.get_cmap('Spectral')) for label, x, y in zip(labels, data[:, 0], data[:, 1]): plt.annotate( label, xy=(x, y), xytext=(-20, 20), textcoords='offset points', ha='right', va='bottom', bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0')) plt.show() ```",465 "best_answers_score":0.8,466 "library_name":"matplotlib",467 "question_url":"https:\/\/stackoverflow.com\/questions\/5147112\/how-to-put-individual-tags-for-a-matplotlib-scatter-plot",468 "best_answers_votes":384,469 "question_length":384,470 "response_length":619471 },472 {473 "question":"How to remove gaps between subplots The code below produces gaps between the subplots. How do I remove the gaps between the subplots and make the image a tight grid? ``` import matplotlib.pyplot as plt for i in range(16): i = i + 1 ax1 = plt.subplot(4, 4, i) plt.axis('on') ax1.set_xticklabels([]) ax1.set_yticklabels([]) ax1.set_aspect('equal') plt.subplots_adjust(wspace=None, hspace=None) plt.show() ```",474 "response":"The problem is the use of aspect='equal', which prevents the subplots from stretching to an arbitrary aspect ratio and filling up all the empty space. Normally, this would work: ``` import matplotlib.pyplot as plt ax = [plt.subplot(2,2,i+1) for i in range(4)] for a in ax: a.set_xticklabels([]) a.set_yticklabels([]) plt.subplots_adjust(wspace=0, hspace=0) ``` The result is this: However, with aspect='equal', as in the following code: ``` import matplotlib.pyplot as plt ax = [plt.subplot(2,2,i+1) for i in range(4)] for a in ax: a.set_xticklabels([]) a.set_yticklabels([]) a.set_aspect('equal') plt.subplots_adjust(wspace=0, hspace=0) ``` This is what we get: The difference in this second case is that you've forced the x- and y-axes to have the same number of units\/pixel. Since the axes go from 0 to 1 by default (i.e., before you plot anything), using aspect='equal' forces each axis to be a square. Since the figure is not a square, pyplot adds in extra spacing between the axes horizontally. To get around this problem, you can set your figure to have the correct aspect ratio. We're going to use the object-oriented pyplot interface here, which I consider to be superior in general: ``` import matplotlib.pyplot as plt fig = plt.figure(figsize=(8,8)) # Notice the equal aspect ratio ax = [fig.add_subplot(2,2,i+1) for i in range(4)] for a in ax: a.set_xticklabels([]) a.set_yticklabels([]) a.set_aspect('equal') fig.subplots_adjust(wspace=0, hspace=0) ``` Here's the result:",475 "best_answers_score":0.8,476 "library_name":"matplotlib",477 "question_url":"https:\/\/stackoverflow.com\/questions\/20057260\/how-to-remove-gaps-between-subplots",478 "best_answers_votes":268,479 "question_length":406,480 "response_length":1484481 },482 {483 "question":"Plotting time on the independent axis I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array. Can I plot time on the x axis and the numbers on the y-axis using Matplotlib? I was trying to, but somehow it was only accepting arrays of floats. How can I get it to plot the time? Do I have to modify the format in any way?",484 "response":"Update: This answer is outdated since matplotlib version 3.5. The plot function now handles datetime data directly. See https:\/\/matplotlib.org\/3.5.1\/api\/_as_gen\/matplotlib.pyplot.plot_date.html The use of plot_date is discouraged. This method exists for historic reasons and may be deprecated in the future. datetime-like data should directly be plotted using plot. If you need to plot plain numeric data as Matplotlib date format or need to set a timezone, call ax.xaxis.axis_date \/ ax.yaxis.axis_date before plot. See Axis.axis_date. Old, outdated answer: You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format. Plot the dates and values using plot_date: ``` import matplotlib.pyplot as plt import matplotlib.dates from datetime import datetime x_values = [datetime(2021, 11, 18, 12), datetime(2021, 11, 18, 14), datetime(2021, 11, 18, 16)] y_values = [1.0, 3.0, 2.0] dates = matplotlib.dates.date2num(x_values) plt.plot_date(dates, y_values) ```",485 "best_answers_score":0.8,486 "library_name":"matplotlib",487 "question_url":"https:\/\/stackoverflow.com\/questions\/1574088\/plotting-time-on-the-independent-axis",488 "best_answers_votes":226,489 "question_length":423,490 "response_length":1044491 },492 {493 "question":"How do I tell matplotlib that I am done with a plot? The following code plots to two PostScript (.ps) files, but the second one contains both lines. ``` import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.subplot(111) x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls=\"-\") plt.savefig(\"first.ps\") plt.subplot(111) x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls=\"-\") plt.savefig(\"second.ps\") ``` How can I tell matplotlib to start afresh for the second plot?",494 "response":"There is a clear figure command, and it should do it for you: ``` plt.clf() ``` If you have multiple subplots in the same figure ``` plt.cla() ``` clears the current axes.",495 "best_answers_score":0.8,496 "library_name":"matplotlib",497 "question_url":"https:\/\/stackoverflow.com\/questions\/741877\/how-do-i-tell-matplotlib-that-i-am-done-with-a-plot",498 "best_answers_votes":227,499 "question_length":528,500 "response_length":171501 },502 {503 "question":"How do I create a second (new) plot, then later plot on the old one? I want to plot data, then create a new figure and plot data2, and finally come back to the original plot and plot data3, kinda like this: ``` import numpy as np import matplotlib as plt x = arange(5) y = np.exp(5) plt.figure() plt.plot(x, y) z = np.sin(x) plt.figure() plt.plot(x, z) w = np.cos(x) plt.figure(\"\"\"first figure\"\"\") # Here's the part I need plt.plot(x, w) ``` FYI How do I tell matplotlib that I am done with a plot? does something similar, but not quite! It doesn't let me get access to that original plot.",504 "response":"If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case: ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(5) y = np.exp(x) fig1, ax1 = plt.subplots() ax1.plot(x, y) ax1.set_title(\"Axis 1 title\") ax1.set_xlabel(\"X-label for axis 1\") z = np.sin(x) fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure ax2.plot(x, z) ax3.plot(x, -z) w = np.cos(x) ax1.plot(x, w) # can continue plotting on the first axis ``` It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.",505 "best_answers_score":0.8,506 "library_name":"matplotlib",507 "question_url":"https:\/\/stackoverflow.com\/questions\/6916978\/how-do-i-create-a-second-new-plot-then-later-plot-on-the-old-one",508 "best_answers_votes":197,509 "question_length":589,510 "response_length":668511 },512 {513 "question":"What is the difference between pylab and pyplot? [duplicate] This question already has answers here: Which is the recommended way to plot: matplotlib or pylab? (2 answers) Closed 4 years ago. What is the difference between matplotlib.pyplot and matplotlib.pylab? Which is preferred for what usage? I am a little confused, because it seems like independent from which I import, I can do the same things. What am I missing?",514 "response":"This wording is no longer in the documentation. Use of the pylab import is now discouraged and the OO interface is recommended for most non-interactive usage. From the documentation, the emphasis is mine: Matplotlib is the whole package; pylab is a module in matplotlib that gets installed alongside matplotlib; and matplotlib.pyplot is a module in matplotlib. Pyplot provides the state-machine interface to the underlying plotting library in matplotlib. This means that figures and axes are implicitly and automatically created to achieve the desired plot. For example, calling plot from pyplot will automatically create the necessary figure and axes to achieve the desired plot. Setting a title will then automatically set that title to the current axes object: Pylab combines the pyplot functionality (for plotting) with the numpy functionality (for mathematics and for working with arrays) in a single namespace, making that namespace (or environment) even more MATLAB-like. For example, one can call the sin and cos functions just like you could in MATLAB, as well as having all the features of pyplot. The pyplot interface is generally preferred for non-interactive plotting (i.e., scripting). The pylab interface is convenient for interactive calculations and plotting, as it minimizes typing. Note that this is what you get if you use the ipython shell with the -pylab option, which imports everything from pylab and makes plotting fully interactive.",515 "best_answers_score":0.8,516 "library_name":"matplotlib",517 "question_url":"https:\/\/stackoverflow.com\/questions\/11469336\/what-is-the-difference-between-pylab-and-pyplot",518 "best_answers_votes":175,519 "question_length":421,520 "response_length":1458521 },522 {523 "question":"How to plot a high resolution graph I've used matplotlib for plotting some experimental results (discussed it in here: Looping over files and plotting. However, saving the picture by clicking right to the image gives very bad quality \/ low resolution images. ``` from glob import glob import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl # loop over all files in the current directory ending with .txt for fname in glob(\".\/*.txt\"): # read file, skip header (1 line) and unpack into 3 variables WL, ABS, T = np.genfromtxt(fname, skip_header=1, unpack=True) # first plot plt.plot(WL, T, label='BN', color='blue') plt.xlabel('Wavelength (nm)') plt.xlim(200,1000) plt.ylim(0,100) plt.ylabel('Transmittance, %') mpl.rcParams.update({'font.size': 14}) #plt.legend(loc='lower center') plt.title('') plt.show() plt.clf() # second plot plt.plot(WL, ABS, label='BN', color='red') plt.xlabel('Wavelength (nm)') plt.xlim(200,1000) plt.ylabel('Absorbance, A') mpl.rcParams.update({'font.size': 14}) #plt.legend() plt.title('') plt.show() plt.clf() ``` Example graph of what I'm looking for: example graph",524 "response":"You can use savefig() to export to an image file: ``` plt.savefig('filename.png') ``` In addition, you can specify the dpi argument to some scalar value (default is 100). For example: ``` plt.savefig('filename.png', dpi=300) ```",525 "best_answers_score":0.8,526 "library_name":"matplotlib",527 "question_url":"https:\/\/stackoverflow.com\/questions\/39870642\/how-to-plot-a-high-resolution-graph",528 "best_answers_votes":303,529 "question_length":1114,530 "response_length":228531 },532 {533 "question":"Matplotlib: draw grid lines behind other graph elements In Matplotlib, I make dashed grid lines as follows: ``` fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.yaxis.grid(color='gray', linestyle='dashed') ``` however, I can't find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bars. Changing the order of adding the grid versus adding other elements makes no difference. Is it possible to make it so that the grid lines appear behind everything else?",534 "response":"According to this - https:\/\/web.archive.org\/web\/20200131000410\/http:\/\/matplotlib.1069221.n5.nabble.com\/axis-elements-and-zorder-td5346.html - you can use Axis.set_axisbelow(True) (I am currently installing matplotlib for the first time, so have no idea if that's correct - I just found it by googling \"matplotlib z order grid\" - \"z order\" is typically used to describe this kind of thing (z being the axis \"out of the page\"))",535 "best_answers_score":0.8,536 "library_name":"matplotlib",537 "question_url":"https:\/\/stackoverflow.com\/questions\/1726391\/matplotlib-draw-grid-lines-behind-other-graph-elements",538 "best_answers_votes":205,539 "question_length":513,540 "response_length":425541 },542 {543 "question":"Bin size in Matplotlib (Histogram) I'm using matplotlib to make a histogram. Is there any way to manually set the size of the bins as opposed to the number of bins?",544 "response":"Actually, it's quite easy: instead of the number of bins you can give a list with the bin boundaries. They can be unequally distributed, too: ``` plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100]) ``` If you just want them equally distributed, you can simply use range: ``` plt.hist(data, bins=range(min(data), max(data) + binwidth, binwidth)) ``` Added to original answer The above line works for data filled with integers only. As macrocosme points out, for floats you can use: ``` import numpy as np plt.hist(data, bins=np.arange(min(data), max(data) + binwidth, binwidth)) ```",545 "best_answers_score":0.8,546 "library_name":"matplotlib",547 "question_url":"https:\/\/stackoverflow.com\/questions\/6986986\/bin-size-in-matplotlib-histogram",548 "best_answers_votes":358,549 "question_length":164,550 "response_length":579551 },552 {553 "question":"How to display an image I tried to use IPython.display with the following code: ``` from IPython.display import display, Image display(Image(filename='MyImage.png')) ``` I also tried to use matplotlib with the following code: ``` import matplotlib.pyplot as plt import matplotlib.image as mpimg plt.imshow(mpimg.imread('MyImage.png')) ``` In both cases, nothing is displayed, not even an error message.",554 "response":"If you are using matplotlib and want to show the image in your interactive notebook, try the following: ``` %matplotlib inline import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('your_image.png') imgplot = plt.imshow(img) plt.show() ```",555 "best_answers_score":0.8,556 "library_name":"matplotlib",557 "question_url":"https:\/\/stackoverflow.com\/questions\/35286540\/how-to-display-an-image",558 "best_answers_votes":388,559 "question_length":402,560 "response_length":269561 },562 {563 "question":"Generating matplotlib graphs without a running X server [duplicate] This question already has answers here: Generating a PNG with matplotlib when DISPLAY is undefined (13 answers) Closed 11 years ago. Matplotlib seems to require the $DISPLAY environment variable which means a running X server.Some web hosting services do not allow a running X server session.Is there a way to generate graphs using matplotlib without a running X server? ``` [username@hostname ~]$ python2.6 Python 2.6.5 (r265:79063, Nov 23 2010, 02:02:03) [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 Type \"help\", \"copyright\", \"credits\" or \"license\" for more information. >>> import matplotlib.pyplot as plt >>> fig = plt.figure() Traceback (most recent call last): File \"\", line 1, in File \"\/home\/username\/lib\/python2.6\/matplotlib-1.0.1-py2.6-linux-i686.egg\/matplotlib\/pyplot.py\", line 270, in figure **kwargs) File \"\/home\/username\/lib\/python2.6\/matplotlib-1.0.1-py2.6-linux-i686.egg\/matplotlib\/backends\/backend_tkagg.py\", line 80, in new_figure_manager window = Tk.Tk() File \"\/usr\/local\/lib\/python2.6\/lib-tk\/Tkinter.py\", line 1643, in __init__ self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: no display name and no $DISPLAY environment variable >>> ```",564 "response":"@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg') before importing matplotlib.pyplot, and then continue as normal. E.g. ``` import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot(range(10)) fig.savefig('temp.png') ``` You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install. Alternately, you can just set the backend parameter in your .matplotlibrc file to automatically have matplotlib.pyplot use the given renderer.",565 "best_answers_score":0.8,566 "library_name":"matplotlib",567 "question_url":"https:\/\/stackoverflow.com\/questions\/4931376\/generating-matplotlib-graphs-without-a-running-x-server",568 "best_answers_votes":362,569 "question_length":1303,570 "response_length":784571 },572 {573 "question":"How to export plots from matplotlib with transparent background? I am using matplotlib to make some graphs and unfortunately I cannot export them without the white background. In other words, when I export a plot like this and position it on top of another image, the white background hides what is behind it rather than allowing it to show through. How can I export plots with a transparent background instead?",574 "response":"Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file. ``` In [28]: import numpy as np In [29]: from matplotlib.pyplot import plot, savefig In [30]: x = np.linspace(0,6,31) In [31]: y = np.exp(-0.5*x) * np.sin(x) In [32]: plot(x, y, 'bo-') Out[32]: [] In [33]: savefig('demo.png', transparent=True) ``` Result: Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.",575 "best_answers_score":0.8,576 "library_name":"matplotlib",577 "question_url":"https:\/\/stackoverflow.com\/questions\/15857647\/how-to-export-plots-from-matplotlib-with-transparent-background",578 "best_answers_votes":293,579 "question_length":411,580 "response_length":617581 },582 {583 "question":"Saving images in Python at a very high quality How can I save Python plots at very high quality? That is, when I keep zooming in on the object saved in a PDF file, why isn't there any blurring? Also, what would be the best mode to save it in? png, eps? Or some other? I can't do pdf, because there is a hidden number that happens that mess with Latexmk compilation.",584 "response":"If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image: ``` plt.savefig('destination_path.eps', format='eps') ``` I have found that EPS files work best and the dpi parameter is what really makes them look good in a document. To specify the orientation of the figure before saving, simply call the following before the plt.savefig call, but after creating the plot (assuming you have plotted using an axes with the name ax): ``` ax.view_init(elev=elevation_angle, azim=azimuthal_angle) ``` Where elevation_angle is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle specifies the azimuthal angle (around the z axis). I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.",585 "best_answers_score":0.8,586 "library_name":"matplotlib",587 "question_url":"https:\/\/stackoverflow.com\/questions\/16183462\/saving-images-in-python-at-a-very-high-quality",588 "best_answers_votes":232,589 "question_length":365,590 "response_length":1157591 },592 {593 "question":"Plotting a list of (x, y) coordinates I have a list of pairs (a, b) that I would like to plot with matplotlib in python as actual x-y coordinates. Currently, it is making two plots, where the index of the list gives the x-coordinate, and the first plot's y values are the as in the pairs and the second plot's y values are the bs in the pairs. To clarify, my data looks like this: li = [(a,b), (c,d), ... , (t, u)] and I want to do a one-liner that just calls plt.plot(). If I didn't require a one-liner I could trivially do: ```py xs = [x[0] for x in li] ys = [x[1] for x in li] plt.plot(xs, ys) ``` How can I get matplotlib to plot these pairs as x-y coordinates? Sample data ```py # sample data li = list(zip(range(1, 14), range(14, 27))) li \u2192 [(1, 14), (2, 15), (3, 16), (4, 17), (5, 18), (6, 19), (7, 20), (8, 21), (9, 22), (10, 23), (11, 24), (12, 25), (13, 26)] ``` Incorrect Plot ```py plt.plot(li) plt.title('Incorrect Plot:\\nEach index of the tuple plotted as separate lines') ``` Desired Plot This produces the correct plot, but to many lines of code are used to unpack li. I need to unpack and plot with a single line of code, not multiple list-comprehensions. ```py xs = [x[0] for x in li] ys = [x[1] for x in li] plt.plot(xs, ys) plt.title('Correct Plot:\\nBut uses to many lines to unpack li') ```",594 "response":"Given li in the question: ``` li = list(zip(range(1, 14), range(14, 27))) ``` To unpack the data from pairs into lists use zip: ``` x, y = zip(*li) x \u2192 (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) y \u2192 (14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26) ``` The one-liner uses the unpacking operator (*), to unpack the list of tuples for zip, and unpacks the zip object into the plot API. ``` plt.scatter(*zip(*li)) ``` ``` plt.plot(*zip(*li)) ```",595 "best_answers_score":0.8,596 "library_name":"matplotlib",597 "question_url":"https:\/\/stackoverflow.com\/questions\/21519203\/plotting-a-list-of-x-y-coordinates",598 "best_answers_votes":280,599 "question_length":1311,600 "response_length":446601 },602 {603 "question":"Plt.show shows full graph but savefig is cropping the image My code is succesfully saving images to file, but it is cropping important details from the right hand side. Answers exist for fixing this problem when it arises for plt.show, but it is the savefig command that is incorrectly producing the graph in this example. How can this be fixed? The relevant sample of my code: ``` import glob import os for file in glob.glob(\"*.oax\"): try: spc_file = open(file, 'r').read() newName = file[6:8] + '-' + file[4:6] + '-' + file[0:4] + ' ' + file[8:12] + ' UTC (Observed) - No Sea Breeze Day' plt.title(newName, fontsize=12, loc='left') plt.savefig('X:\/' + newName + '.png') plt.show() except Exception: pass ``` And the images (top is plt.show and bottom is file produced from savefig:",604 "response":"You may try ``` plt.savefig('X:\/' + newName + '.png', bbox_inches='tight') ``` Or you may define figure size like ``` fig = plt.figure(figsize=(9, 11)) ... plt.savefig(filename, bbox_inches = 'tight') ```",605 "best_answers_score":0.8,606 "library_name":"matplotlib",607 "question_url":"https:\/\/stackoverflow.com\/questions\/37427362\/plt-show-shows-full-graph-but-savefig-is-cropping-the-image",608 "best_answers_votes":351,609 "question_length":783,610 "response_length":204611 },612 {613 "question":"Plot smooth line with PyPlot I've got the following simple script that plots a graph: ``` import matplotlib.pyplot as plt import numpy as np T = np.array([6, 7, 8, 9, 10, 11, 12]) power = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00]) plt.plot(T,power) plt.show() ``` As it is now, the line goes straight from point to point which looks ok, but could be better in my opinion. What I want is to smooth the line between the points. In Gnuplot I would have plotted with smooth cplines. Is there an easy way to do this in PyPlot? I've found some tutorials, but they all seem rather complex.",614 "response":"You could use scipy.interpolate.spline to smooth out your data yourself: ``` from scipy.interpolate import spline # 300 represents number of points to make between T.min and T.max xnew = np.linspace(T.min(), T.max(), 300) power_smooth = spline(T, power, xnew) plt.plot(xnew,power_smooth) plt.show() ``` spline is deprecated in scipy 0.19.0, use BSpline class instead. Switching from spline to BSpline isn't a straightforward copy\/paste and requires a little tweaking: ``` from scipy.interpolate import make_interp_spline, BSpline # 300 represents number of points to make between T.min and T.max xnew = np.linspace(T.min(), T.max(), 300) spl = make_interp_spline(T, power, k=3) # type: BSpline power_smooth = spl(xnew) plt.plot(xnew, power_smooth) plt.show() ``` Before: After:",615 "best_answers_score":0.8,616 "library_name":"matplotlib",617 "question_url":"https:\/\/stackoverflow.com\/questions\/5283649\/plot-smooth-line-with-pyplot",618 "best_answers_votes":231,619 "question_length":620,620 "response_length":777621 },622 {623 "question":"How to rotate x-axis tick labels in a pandas plot With the following code: ``` import matplotlib matplotlib.style.use('ggplot') import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({ 'celltype':[\"foo\",\"bar\",\"qux\",\"woz\"], 's1':[5,9,1,7], 's2':[12,90,13,87]}) df = df[[\"celltype\",\"s1\",\"s2\"]] df.set_index([\"celltype\"],inplace=True) df.plot(kind='bar',alpha=0.75) plt.xlabel(\"\") ``` I made this plot: How can I rotate the x-axis tick labels to 0 degrees? I tried adding this but did not work: ``` plt.set_xticklabels(df.index,rotation=90) ```",624 "response":"Pass param rot=0 to rotate the xticklabels: ``` import matplotlib matplotlib.style.use('ggplot') import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({ 'celltype':[\"foo\",\"bar\",\"qux\",\"woz\"], 's1':[5,9,1,7], 's2':[12,90,13,87]}) df = df[[\"celltype\",\"s1\",\"s2\"]] df.set_index([\"celltype\"],inplace=True) df.plot(kind='bar',alpha=0.75, rot=0) plt.xlabel(\"\") plt.show() ``` yields plot:",625 "best_answers_score":0.8,626 "library_name":"matplotlib",627 "question_url":"https:\/\/stackoverflow.com\/questions\/32244019\/how-to-rotate-x-axis-tick-labels-in-a-pandas-plot",628 "best_answers_votes":329,629 "question_length":556,630 "response_length":396631 },632 {633 "question":"What is the difference between drawing plots using plot, axes or figure in matplotlib? I'm kind of confused what is going at the backend when I draw plots in matplotlib, tbh, I'm not clear with the hierarchy of plot, axes and figure. I read the documentation and it was helpful but I'm still confused... The below code draws the same plot in three different ways - ``` #creating the arrays for testing x = np.arange(1, 100) y = np.sqrt(x) #1st way plt.plot(x, y) #2nd way ax = plt.subplot() ax.plot(x, y) #3rd way figure = plt.figure() new_plot = figure.add_subplot(111) new_plot.plot(x, y) ``` Now my question is - What is the difference between all the three, I mean what is going under the hood when any of the 3 methods are called? Which method should be used when and what are the pros and cons of using any on those?",634 "response":"The names of objects Matplotlib is strongly object oriented and its principal objects are the figure and the axes(1). You can think of the figure as a canvas, of which you typically specify the dimensions and possibly e.g., the background color etc etc. You use the canvas, the figure, essentially in two ways, placing other objects on it (mostly axes, but also text labels etc) and saving its contents with savefig. You can think of an axes as a sort of Swiss Army knife, a handy object that offers a tool (e.g. .plot, .scatter, .hist etc) for everything, mostly. You can place one, two, ... many axes inside a figure using one of many different methods. The plt interface The plt procedural interface was originally developed to mimic the MATLAB\u2122 interface but is not really different from the object oriented interface, even if you don't make a direct reference to the main objects (i.e., a figure and an axes) these objects are automatically instantiated and each plt method is, essentially, translated to a call of one of the methods of the underlying fundamental objects: e.g., a plt.plot() is a hidden_axes.plot and a plt.savefig is a hidden_figure.savefig. In every moment you can have an handle on these hidden objects using plt.gcf and plt.gca, and this is sometimes necessary when one of the object methods has not been ported to a method in the plt namespace. I'd like to add that the plt namespace contains also a number of convenience methods(2) to instantiate, in different ways, figure and axes. Your examples 1st way ``` plt.plot(x, y) ``` Here you use only the plt interface, you can only use a single axes in each figure, but this is what you want when you are doing an exploration of your data, a quick recipe that gets the work done... 2nd way ``` ax = plt.subplot() ax.plot(x, y) ``` Here you use a convenience method in the plt namespace to give a name (and a handle) to your axes object, but btw there is also an hidden figure. You can later use the axes object to plot, to make an histogram etc, all things that you can do with the plt interface, but you can also access all its attributes and modify them with greater freedom. 3rd way ``` figure = plt.figure() new_plot = figure.add_subplot(111) new_plot.plot(x, y) ``` Here you start instantiating a figure using a convenience method in the plt namespace and later you use only the object oriented interface. It is possible to bypass the plt convenience method (matplotlib.figure.Figure) but you then have to tweak the figure for a better interactive experience (after all, it's a convenience method). Personal recommendations I suggest bare plt.plot, plt.scatter in the context of an interactive session, possibly using IPython with its %matplotlib magic command, and also in the context of an exploratory Jupyter notebook. On the other hand the object oriented approach, plus a few plt convenience methods(2), is the way to go if you have a permanent issue to solve once for all with a customized arrangement of finely tuned subplots, if you want to embed Matplotlib in the UI of a program you write. There is a large gray area between these extremes and if you ask me what to do I'd just say \"It depends\"... (1) I find the name axes a bit misleading, but probably it's just me. (2) The convenience methods in the plt name space are REALLY CONVENIENT! In particular, when you instantiate Figures and Axes using them, all the minute details needed to deal with interactive windows are automatically taken into account.",635 "best_answers_score":0.8,636 "library_name":"matplotlib",637 "question_url":"https:\/\/stackoverflow.com\/questions\/37970424\/what-is-the-difference-between-drawing-plots-using-plot-axes-or-figure-in-matpl",638 "best_answers_votes":115,639 "question_length":822,640 "response_length":3496641 },642 {643 "question":"Remove or adapt border of frame of legend using matplotlib When plotting a plot using matplotlib: How to remove the box of the legend? How to change the color of the border of the legend box? How to remove only the border of the box of the legend?",644 "response":"When plotting a plot using matplotlib: How to remove the box of the legend? ``` plt.legend(frameon=False) ``` How to change the color of the border of the legend box? ``` leg = plt.legend() leg.get_frame().set_edgecolor('b') ``` How to remove only the border of the box of the legend? ``` leg = plt.legend() leg.get_frame().set_linewidth(0.0) ``` For the matplotlib object oriented approach: ``` axes.legend(frameon=False) leg = axes.legend() leg.get_frame().set_edgecolor('b') leg.get_frame().set_linewidth(0.0) ```",645 "best_answers_score":0.8,646 "library_name":"matplotlib",647 "question_url":"https:\/\/stackoverflow.com\/questions\/25540259\/remove-or-adapt-border-of-frame-of-legend-using-matplotlib",648 "best_answers_votes":327,649 "question_length":247,650 "response_length":516651 },652 {653 "question":"How to pick a new color for each plotted line within a figure I'd like to NOT specify a color for each plotted line, and have each line get a distinct color. But if I run: ``` from matplotlib import pyplot as plt for i in range(20): plt.plot([0, 1], [i, i]) plt.show() ``` then I get this output: If you look at the image above, you can see that matplotlib attempts to pick colors for each line that are different, but eventually it re-uses colors - the top ten lines use the same colors as the bottom ten. I just want to stop it from repeating already used colors AND\/OR feed it a list of colors to use.",654 "response":"I usually use the second one of these: ```py from matplotlib.pyplot import cm import numpy as np #variable n below should be number of curves to plot #version 1: color = cm.rainbow(np.linspace(0, 1, n)) for i, c in enumerate(color): plt.plot(x, y, c=c) #or version 2: color = iter(cm.rainbow(np.linspace(0, 1, n))) for i in range(n): c = next(color) plt.plot(x, y, c=c) ``` Example of 2:",655 "best_answers_score":0.8,656 "library_name":"matplotlib",657 "question_url":"https:\/\/stackoverflow.com\/questions\/4971269\/how-to-pick-a-new-color-for-each-plotted-line-within-a-figure",658 "best_answers_votes":223,659 "question_length":604,660 "response_length":387661 },662 {663 "question":"matplotlib: colorbars and its text labels I'd like to create a colorbar legend for a heatmap, such that the labels are in the center of each discrete color. Example borrowed from here: ``` import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap #discrete color scheme cMap = ListedColormap(['white', 'green', 'blue','red']) #data np.random.seed(42) data = np.random.rand(4, 4) fig, ax = plt.subplots() heatmap = ax.pcolor(data, cmap=cMap) #legend cbar = plt.colorbar(heatmap) cbar.ax.set_yticklabels(['0','1','2','>3']) cbar.set_label('# of contacts', rotation=270) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) ax.invert_yaxis() #labels column_labels = list('ABCD') row_labels = list('WXYZ') ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(row_labels, minor=False) plt.show() ``` This generates the following plot: Ideally I'd like to generate a legend bar which has the four colors and for each color, a label in its center: 0,1,2,>3. How can this be achieved?",664 "response":"``` import matplotlib.pyplot as plt import numpy as np from matplotlib.colors import ListedColormap #discrete color scheme cMap = ListedColormap(['white', 'green', 'blue','red']) #data np.random.seed(42) data = np.random.rand(4, 4) fig, ax = plt.subplots() heatmap = ax.pcolor(data, cmap=cMap) #legend cbar = plt.colorbar(heatmap) cbar.ax.get_yaxis().set_ticks([]) for j, lab in enumerate(['$0$','$1$','$2$','$>3$']): cbar.ax.text(.5, (2 * j + 1) \/ 8.0, lab, ha='center', va='center') cbar.ax.get_yaxis().labelpad = 15 cbar.ax.set_ylabel('# of contacts', rotation=270) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) ax.invert_yaxis() #labels column_labels = list('ABCD') row_labels = list('WXYZ') ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(row_labels, minor=False) plt.show() ``` You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.",665 "best_answers_score":0.8,666 "library_name":"matplotlib",667 "question_url":"https:\/\/stackoverflow.com\/questions\/15908371\/matplotlib-colorbars-and-its-text-labels",668 "best_answers_votes":192,669 "question_length":1141,670 "response_length":1142671 },672 {673 "question":"A tool to convert MATLAB code to Python [closed] Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting answers. We don\u2019t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations. Closed 9 years ago. Improve this question I have a bunch of MATLAB code from my MS thesis which I now want to convert to Python (using numpy\/scipy and matplotlib) and distribute as open-source. I know the similarity between MATLAB and Python scientific libraries, and converting them manually will be not more than a fortnight (provided that I work towards it every day for some time). I was wondering if there was already any tool available which can do the conversion.",674 "response":"There are several tools for converting Matlab to Python code. The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp). Other options include: LiberMate: translate from Matlab to Python and SciPy (Requires Python 2, last update 4 years ago). OMPC: Matlab to Python (a bit outdated). Mat2py: Matlab to Python (Requires Python 2). Also, for those interested in an interface between the two languages and not conversion: pymatlab: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data. Python-Matlab wormholes: both directions of interaction supported. Python-Matlab bridge: use Matlab from within Python, offers matlab_magic for iPython, to execute normal matlab code from within ipython. PyMat: Control Matlab session from Python. pymat2: continuation of the seemingly abandoned PyMat. mlabwrap, mlabwrap-purepy: make Matlab look like Python library (based on PyMat). oct2py (repository): run GNU Octave commands from within Python. pymex: Embeds the Python Interpreter in Matlab, also on File Exchange. matpy: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed). MatPy: Python package for numerical linear algebra and plotting with a MatLab-like interface. Btw might be helpful to look here for other migration tips: http:\/\/bci2000.org\/downloads\/BCPy2000\/Migration.html On a different note, for people who might find it useful there is: matlab2fortran",675 "best_answers_score":0.8,676 "library_name":"matplotlib",677 "question_url":"https:\/\/stackoverflow.com\/questions\/9845292\/a-tool-to-convert-matlab-code-to-python",678 "best_answers_votes":186,679 "question_length":930,680 "response_length":1596681 },682 {683 "question":"How to share x axes of two subplots after they have been created I'm trying to share two subplots axes, but I need to share the x axis after the figure was created. E.g. I create this figure: ```py import numpy as np import matplotlib.pyplot as plt t = np.arange(1000)\/100. x = np.sin(2*np.pi*10*t) y = np.cos(2*np.pi*10*t) fig = plt.figure() ax1 = plt.subplot(211) plt.plot(t,x) ax2 = plt.subplot(212) plt.plot(t,y) # some code to share both x axes plt.show() ``` Instead of the comment I want to insert some code to share both x axes. How do I do this? There are some relevant sounding attributes _shared_x_axes and _shared_x_axes when I check to figure axis (fig.get_axes()) but I don't know how to link them.",684 "response":"The usual way to share axes is to create the shared properties at creation. Either ``` fig=plt.figure() ax1 = plt.subplot(211) ax2 = plt.subplot(212, sharex = ax1) ``` or ``` fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True) ``` Sharing the axes after they have been created should therefore not be necessary. However if for any reason, you need to share axes after they have been created (actually, using a different library which creates some subplots, like here might be a reason), there would still be a solution: Using ``` ax2.sharex(ax1) ``` creates a link between the two axes, ax1 and ax2. In contrast to the sharing at creation time, you will have to set the xticklabels off manually for one of the axes (in case that is wanted). A complete example: ``` import numpy as np import matplotlib.pyplot as plt t= np.arange(1000)\/100. x = np.sin(2*np.pi*10*t) y = np.cos(2*np.pi*10*t) fig=plt.figure() ax1 = plt.subplot(211) ax2 = plt.subplot(212) ax1.plot(t,x) ax2.plot(t,y) ax2.sharex(ax1) ax1.set_xticklabels([]) # ax2.autoscale() ## call autoscale if needed plt.show() ``` For a list of axes you would do: ``` for ax in axes[1:]: ax.sharex(axes[0]) ```",685 "best_answers_score":0.8,686 "library_name":"matplotlib",687 "question_url":"https:\/\/stackoverflow.com\/questions\/42973223\/how-to-share-x-axes-of-two-subplots-after-they-have-been-created",688 "best_answers_votes":265,689 "question_length":712,690 "response_length":1162691 },692 {693 "question":"How to connect scatterplot points with line using matplotlib I have two lists, dates and values. I want to plot them using matplotlib. The following creates a scatter plot of my data. ```py import matplotlib.pyplot as plt plt.scatter(dates,values) plt.show() ``` plt.plot(dates, values) creates a line graph. But what I really want is a scatterplot where the points are connected by a line. Similar to in R: ```r plot(dates, values) lines(dates, value, type=\"l\") ``` which gives me a scatterplot of points overlaid with a line connecting the points. How do I do this in python?",694 "response":"I think @Evert has the right answer: ``` plt.scatter(dates,values) plt.plot(dates, values) plt.show() ``` Which is pretty much the same as ``` plt.plot(dates, values, '-o') plt.show() ``` You can replace -o with another suitable format string as described in the documentation. You can also split the choices of line and marker styles using the linestyle= and marker= keyword arguments.",695 "best_answers_score":0.8,696 "library_name":"matplotlib",697 "question_url":"https:\/\/stackoverflow.com\/questions\/20130227\/how-to-connect-scatterplot-points-with-line-using-matplotlib",698 "best_answers_votes":224,699 "question_length":577,700 "response_length":386701 },702 {703 "question":"How to plot multiple functions on the same figure How can I plot the following 3 functions (i.e. sin, cos and the addition), on the domain t, in the same figure? ```py import numpy as np import matplotlib.pyplot as plt t = np.linspace(0, 2*np.pi, 400) a = np.sin(t) b = np.cos(t) c = a + b ```",704 "response":"To plot multiple graphs on the same figure you will have to do: ``` from numpy import * import math import matplotlib.pyplot as plt t = linspace(0, 2*math.pi, 400) a = sin(t) b = cos(t) c = a + b plt.plot(t, a, 'r') # plotting t, a separately plt.plot(t, b, 'b') # plotting t, b separately plt.plot(t, c, 'g') # plotting t, c separately plt.show() ```",705 "best_answers_score":0.8,706 "library_name":"matplotlib",707 "question_url":"https:\/\/stackoverflow.com\/questions\/22276066\/how-to-plot-multiple-functions-on-the-same-figure",708 "best_answers_votes":263,709 "question_length":293,710 "response_length":351711 },712 {713 "question":"Moving x-axis to the top of a plot in matplotlib Based on this question about heatmaps in matplotlib, I wanted to move the x-axis titles to the top of the plot. ``` import matplotlib.pyplot as plt import numpy as np column_labels = list('ABCD') row_labels = list('WXYZ') data = np.random.rand(4,4) fig, ax = plt.subplots() heatmap = ax.pcolor(data, cmap=plt.cm.Blues) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False) ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False) # want a more natural, table-like display ax.invert_yaxis() ax.xaxis.set_label_position('top') # <-- This doesn't work! ax.set_xticklabels(row_labels, minor=False) ax.set_yticklabels(column_labels, minor=False) plt.show() ``` However, calling matplotlib's set_label_position (as notated above) doesn't seem to have the desired effect. Here's my output: What am I doing wrong?",714 "response":"Use ``` ax.xaxis.tick_top() ``` to place the tick marks at the top of the image. The command ``` ax.set_xlabel('X LABEL') ax.xaxis.set_label_position('top') ``` affects the label, not the tick marks. ``` import matplotlib.pyplot as plt import numpy as np column_labels = list('ABCD') row_labels = list('WXYZ') data = np.random.rand(4, 4) fig, ax = plt.subplots() heatmap = ax.pcolor(data, cmap=plt.cm.Blues) # put the major ticks at the middle of each cell ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False) # want a more natural, table-like display ax.invert_yaxis() ax.xaxis.tick_top() ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(row_labels, minor=False) plt.show() ```",715 "best_answers_score":0.8,716 "library_name":"matplotlib",717 "question_url":"https:\/\/stackoverflow.com\/questions\/14406214\/moving-x-axis-to-the-top-of-a-plot-in-matplotlib",718 "best_answers_votes":242,719 "question_length":906,720 "response_length":760721 },722 {723 "question":"figure of imshow() is too small I'm trying to visualize a numpy array using imshow() since it's similar to imagesc() in Matlab. ``` imshow(random.rand(8, 90), interpolation='nearest') ``` The resulting figure is very small at the center of the grey window, while most of the space is unoccupied. How can I set the parameters to make the figure larger? I tried figsize=(xx,xx) and it's not what I want. Thanks!",724 "response":"If you don't give an aspect argument to imshow, it will use the value for image.aspect in your matplotlibrc. The default for this value in a new matplotlibrc is equal. So imshow will plot your array with equal aspect ratio. If you don't need an equal aspect you can set aspect to auto ``` imshow(random.rand(8, 90), interpolation='nearest', aspect='auto') ``` which gives the following figure If you want an equal aspect ratio you have to adapt your figsize according to the aspect ``` fig, ax = subplots(figsize=(18, 2)) ax.imshow(random.rand(8, 90), interpolation='nearest') tight_layout() ``` which gives you:",725 "best_answers_score":0.8,726 "library_name":"matplotlib",727 "question_url":"https:\/\/stackoverflow.com\/questions\/10540929\/figure-of-imshow-is-too-small",728 "best_answers_votes":215,729 "question_length":409,730 "response_length":612731 },732 {733 "question":"Fill between two vertical lines [duplicate] This question already has answers here: How to highlight specific x-value ranges (2 answers) Closed 3 years ago. I went through the examples in the matplotlib documentation, but it wasn't clear to me how I can make a plot that fills the area between two specific vertical lines. For example, say I want to create a plot between x=0.2 and x=4 (for the full y range of the plot). Should I use fill_between, fill or fill_betweenx? Can I use the where condition for this?",734 "response":"It sounds like you want axvspan, rather than one of the fill between functions. The differences is that axvspan (and axhspan) will fill up the entire y (or x) extent of the plot regardless of how you zoom. For example, let's use axvspan to highlight the x-region between 8 and 14: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot(range(20)) ax.axvspan(8, 14, alpha=0.5, color='red') plt.show() ``` You could use fill_betweenx to do this, but the extents (both x and y) of the rectangle would be in data coordinates. With axvspan, the y-extents of the rectangle default to 0 and 1 and are in axes coordinates (in other words, percentages of the height of the plot). To illustrate this, let's make the rectangle extend from 10% to 90% of the height (instead of taking up the full extent). Try zooming or panning, and notice that the y-extents say fixed in display space, while the x-extents move with the zoom\/pan: ``` import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot(range(20)) ax.axvspan(8, 14, ymin=0.1, ymax=0.9, alpha=0.5, color='red') plt.show() ```",735 "best_answers_score":0.8,736 "library_name":"matplotlib",737 "question_url":"https:\/\/stackoverflow.com\/questions\/23248435\/fill-between-two-vertical-lines",738 "best_answers_votes":324,739 "question_length":511,740 "response_length":1089741 },742 {743 "question":"Hide tick label values but keep axis labels I have this image: ``` plt.plot(sim_1['t'],sim_1['V'],'k') plt.ylabel('V') plt.xlabel('t') plt.show() ``` I want to hide the numbers; if I use: ``` plt.axis('off') ``` ...I get this image: It also hide the labels, V and t. How can I keep the labels while hiding the values?",744 "response":"If you use the matplotlib object-oriented approach, this is a simple task using ax.set_xticklabels() and ax.set_yticklabels(). Here we can just set them to an empty list to remove any labels: ``` import matplotlib.pyplot as plt # Create Figure and Axes instances fig,ax = plt.subplots(1) # Make your plot, set your axes labels ax.plot(sim_1['t'],sim_1['V'],'k') ax.set_ylabel('V') ax.set_xlabel('t') # Turn off tick labels ax.set_yticklabels([]) ax.set_xticklabels([]) plt.show() ``` If you also want to remove the tick marks as well as the labels, you can use ax.set_xticks() and ax.set_yticks() and set those to an empty list as well: ``` ax.set_xticks([]) ax.set_yticks([]) ```",745 "best_answers_score":0.8,746 "library_name":"matplotlib",747 "question_url":"https:\/\/stackoverflow.com\/questions\/37039685\/hide-tick-label-values-but-keep-axis-labels",748 "best_answers_votes":249,749 "question_length":317,750 "response_length":680751 },752 {753 "question":"Prevent scientific notation I have the following code: ``` plt.plot(range(2003,2012,1),range(200300,201200,100)) # several solutions from other questions have not worked, including # plt.ticklabel_format(style='sci', axis='x', scilimits=(-1000000,1000000)) # ax.get_xaxis().get_major_formatter().set_useOffset(False) plt.show() ``` which produces the following plot: How do I prevent scientific notation here? Is ticklabel_format broken? does not resolve the issue of actually removing the offset. ```py plt.plot(np.arange(1e6, 3 * 1e7, 1e6)) plt.ticklabel_format(useOffset=False) ```",754 "response":"In your case, you're actually wanting to disable the offset. Using scientific notation is a separate setting from showing things in terms of an offset value. However, ax.ticklabel_format(useOffset=False) should have worked (though you've listed it as one of the things that didn't). For example: ``` fig, ax = plt.subplots() ax.plot(range(2003,2012,1),range(200300,201200,100)) ax.ticklabel_format(useOffset=False) plt.show() ``` If you want to disable both the offset and scientific notaion, you'd use ax.ticklabel_format(useOffset=False, style='plain'). Difference between \"offset\" and \"scientific notation\" In matplotlib axis formatting, \"scientific notation\" refers to a multiplier for the numbers show, while the \"offset\" is a separate term that is added. Consider this example: ``` import numpy as np import matplotlib.pyplot as plt x = np.linspace(1000, 1001, 100) y = np.linspace(1e-9, 1e9, 100) fig, ax = plt.subplots() ax.plot(x, y) plt.show() ``` The x-axis will have an offset (note the + sign) and the y-axis will use scientific notation (as a multiplier -- No plus sign). We can disable either one separately. The most convenient way is the ax.ticklabel_format method (or plt.ticklabel_format). For example, if we call: ``` ax.ticklabel_format(style='plain') ``` We'll disable the scientific notation on the y-axis: And if we call ``` ax.ticklabel_format(useOffset=False) ``` We'll disable the offset on the x-axis, but leave the y-axis scientific notation untouched: Finally, we can disable both through: ``` ax.ticklabel_format(useOffset=False, style='plain') ```",755 "best_answers_score":0.8,756 "library_name":"matplotlib",757 "question_url":"https:\/\/stackoverflow.com\/questions\/28371674\/prevent-scientific-notation",758 "best_answers_votes":262,759 "question_length":584,760 "response_length":1579761 },762 {763 "question":"How to maximize a plt.show() window Just for curiosity I would like to know how to do this in the code below. I have been searching for an answer but is useless. ``` import numpy as np import matplotlib.pyplot as plt data=np.random.exponential(scale=180, size=10000) print ('el valor medio de la distribucion exponencial es: ') print np.average(data) plt.hist(data,bins=len(data)**0.5,normed=True, cumulative=True, facecolor='red', label='datos tamano paqutes acumulativa', alpha=0.5) plt.legend() plt.xlabel('algo') plt.ylabel('algo') plt.grid() plt.show() ```",764 "response":"I am on a Windows (WIN7), running Python 2.7.5 & Matplotlib 1.3.1. I was able to maximize Figure windows for TkAgg, QT4Agg, and wxAgg using the following lines: ```py from matplotlib import pyplot as plt ### for 'TkAgg' backend plt.figure(1) plt.switch_backend('TkAgg') #TkAgg (instead Qt4Agg) print '#1 Backend:',plt.get_backend() plt.plot([1,2,6,4]) mng = plt.get_current_fig_manager() ### works on Ubuntu??? >> did NOT working on windows # mng.resize(*mng.window.maxsize()) mng.window.state('zoomed') #works fine on Windows! plt.show() #close the figure to run the next section ### for 'wxAgg' backend plt.figure(2) plt.switch_backend('wxAgg') print '#2 Backend:',plt.get_backend() plt.plot([1,2,6,4]) mng = plt.get_current_fig_manager() mng.frame.Maximize(True) plt.show() #close the figure to run the next section ### for 'Qt4Agg' backend plt.figure(3) plt.switch_backend('QT4Agg') #default on my system print '#3 Backend:',plt.get_backend() plt.plot([1,2,6,4]) figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.show() ``` if you want to maximize multiple figures you can use ``` for fig in figs: mng = fig.canvas.manager # ... ``` Hope this summary of the previous answers (and some additions) combined in a working example (at least for windows) helps.",765 "best_answers_score":0.8,766 "library_name":"matplotlib",767 "question_url":"https:\/\/stackoverflow.com\/questions\/12439588\/how-to-maximize-a-plt-show-window",768 "best_answers_votes":212,769 "question_length":561,770 "response_length":1290771 },772 {773 "question":"How to create major and minor gridlines with different linestyles I am currently using matplotlib.pyplot to create graphs and would like to have the major gridlines solid and black and the minor ones either greyed or dashed. In the grid properties, which=both\/major\/mine, and then color and linestyle are defined simply by linestyle. Is there a way to specify minor linestyle only? The appropriate code I have so far is ``` plt.plot(current, counts, 'rd', markersize=8) plt.yscale('log') plt.grid(b=True, which='both', color='0.65', linestyle='-') ```",774 "response":"Actually, it is as simple as setting major and minor separately: ``` In [9]: plot([23, 456, 676, 89, 906, 34, 2345]) Out[9]: [] In [10]: yscale('log') In [11]: grid(visible=True, which='major', color='b', linestyle='-') In [12]: grid(visible=True, which='minor', color='r', linestyle='--') ``` The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log'), but it can also be done with plt.minorticks_on(). Note: before matplotlib 3.5, visible parameter was named b",775 "best_answers_score":0.8,776 "library_name":"matplotlib",777 "question_url":"https:\/\/stackoverflow.com\/questions\/9127434\/how-to-create-major-and-minor-gridlines-with-different-linestyles",778 "best_answers_votes":229,779 "question_length":551,780 "response_length":536781 },782 {783 "question":"Matplotlib discrete colorbar I am trying to make a discrete colorbar for a scatterplot in matplotlib I have my x, y data and for each point an integer tag value which I want to be represented with a unique colour, e.g. ``` plt.scatter(x, y, c=tag) ``` typically tag will be an integer ranging from 0-20, but the exact range may change so far I have just used the default settings, e.g. ``` plt.colorbar() ``` which gives a continuous range of colours. Ideally i would like a set of n discrete colours (n=20 in this example). Even better would be to get a tag value of 0 to produce a gray colour and 1-20 be colourful. I have found some 'cookbook' scripts but they are very complicated and I cannot think they are the right way to solve a seemingly simple problem",784 "response":"You can create a custom discrete colorbar quite easily by using a BoundaryNorm as normalizer for your scatter. The quirky bit (in my method) is making 0 showup as grey. For images i often use the cmap.set_bad() and convert my data to a numpy masked array. That would be much easier to make 0 grey, but i couldnt get this to work with the scatter or the custom cmap. As an alternative you can make your own cmap from scratch, or read-out an existing one and override just some specific entries. ``` import numpy as np import matplotlib as mpl import matplotlib.pylab as plt fig, ax = plt.subplots(1, 1, figsize=(6, 6)) # setup the plot x = np.random.rand(20) # define the data y = np.random.rand(20) # define the data tag = np.random.randint(0, 20, 20) tag[10:12] = 0 # make sure there are some 0 values to show up as grey cmap = plt.cm.jet # define the colormap # extract all colors from the .jet map cmaplist = [cmap(i) for i in range(cmap.N)] # force the first color entry to be grey cmaplist[0] = (.5, .5, .5, 1.0) # create the new map cmap = mpl.colors.LinearSegmentedColormap.from_list( 'Custom cmap', cmaplist, cmap.N) # define the bins and normalize bounds = np.linspace(0, 20, 21) norm = mpl.colors.BoundaryNorm(bounds, cmap.N) # make the scatter scat = ax.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20), cmap=cmap, norm=norm) # create a second axes for the colorbar ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8]) cb = plt.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm, spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i') ax.set_title('Well defined discrete colors') ax2.set_ylabel('Very custom cbar [-]', size=12) ``` I personally think that with 20 different colors its a bit hard to read the specific value, but thats up to you of course.",785 "best_answers_score":0.8,786 "library_name":"matplotlib",787 "question_url":"https:\/\/stackoverflow.com\/questions\/14777066\/matplotlib-discrete-colorbar",788 "best_answers_votes":138,789 "question_length":762,790 "response_length":1774791 },792 {793 "question":"Adding an arbitrary line to a matplotlib plot in ipython notebook I'm rather new to both python\/matplotlib and using it through the ipython notebook. I'm trying to add some annotation lines to an existing graph and I can't figure out how to render the lines on a graph. So, for example, if I plot the following: ``` import numpy as np np.random.seed(5) x = arange(1, 101) y = 20 + 3 * x + np.random.normal(0, 60, 100) p = plot(x, y, \"o\") ``` I get the following graph: So how would I add a vertical line from (70,100) up to (70,250)? What about a diagonal line from (70,100) to (90,200)? I've tried a few things with Line2D() resulting in nothing but confusion on my part. In R I would simply use the segments() function which would add line segments. Is there an equivalent in matplotlib?",794 "response":"You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments): plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2) (of course you can choose the color, line width, line style, etc.) From your example: ``` import numpy as np import matplotlib.pyplot as plt np.random.seed(5) x = np.arange(1, 101) y = 20 + 3 * x + np.random.normal(0, 60, 100) plt.plot(x, y, \"o\") # draw vertical line from (70,100) to (70, 250) plt.plot([70, 70], [100, 250], 'k-', lw=2) # draw diagonal line from (70, 90) to (90, 200) plt.plot([70, 90], [90, 200], 'k-') plt.show() ```",795 "best_answers_score":0.8,796 "library_name":"matplotlib",797 "question_url":"https:\/\/stackoverflow.com\/questions\/12864294\/adding-an-arbitrary-line-to-a-matplotlib-plot-in-ipython-notebook",798 "best_answers_votes":231,799 "question_length":789,800 "response_length":627801 },802 {803 "question":"How to place inline labels in a line plot In Matplotlib, it's not too tough to make a legend (example_legend(), below), but I think it's better style to put labels right on the curves being plotted (as in example_inline(), below). This can be very fiddly, because I have to specify coordinates by hand, and, if I re-format the plot, I probably have to reposition the labels. Is there a way to automatically generate labels on curves in Matplotlib? Bonus points for being able to orient the text at an angle corresponding to the angle of the curve. ``` import numpy as np import matplotlib.pyplot as plt def example_legend(): plt.clf() x = np.linspace(0, 1, 101) y1 = np.sin(x * np.pi \/ 2) y2 = np.cos(x * np.pi \/ 2) plt.plot(x, y1, label='sin') plt.plot(x, y2, label='cos') plt.legend() ``` ``` def example_inline(): plt.clf() x = np.linspace(0, 1, 101) y1 = np.sin(x * np.pi \/ 2) y2 = np.cos(x * np.pi \/ 2) plt.plot(x, y1, label='sin') plt.plot(x, y2, label='cos') plt.text(0.08, 0.2, 'sin') plt.text(0.9, 0.2, 'cos') ```",804 "response":"Update: User cphyc has kindly created a Github repository for the code in this answer (see here), and bundled the code into a package which may be installed using pip install matplotlib-label-lines. Pretty Picture: In matplotlib it's pretty easy to label contour plots (either automatically or by manually placing labels with mouse clicks). There does not (yet) appear to be any equivalent capability to label data series in this fashion! There may be some semantic reason for not including this feature which I am missing. Regardless, I have written the following module which takes any allows for semi-automatic plot labelling. It requires only numpy and a couple of functions from the standard math library. Description The default behaviour of the labelLines function is to space the labels evenly along the x axis (automatically placing at the correct y-value of course). If you want you can just pass an array of the x co-ordinates of each of the labels. You can even tweak the location of one label (as shown in the bottom right plot) and space the rest evenly if you like. In addition, the label_lines function does not account for the lines which have not had a label assigned in the plot command (or more accurately if the label contains '_line'). Keyword arguments passed to labelLines or labelLine are passed on to the text function call (some keyword arguments are set if the calling code chooses not to specify). Issues Annotation bounding boxes sometimes interfere undesirably with other curves. As shown by the 1 and 10 annotations in the top left plot. I'm not even sure this can be avoided. It would be nice to specify a y position instead sometimes. It's still an iterative process to get annotations in the right location It only works when the x-axis values are floats Gotchas By default, the labelLines function assumes that all data series span the range specified by the axis limits. Take a look at the blue curve in the top left plot of the pretty picture. If there were only data available for the x range 0.5-1 then then we couldn't possibly place a label at the desired location (which is a little less than 0.2). See this question for a particularly nasty example. Right now, the code does not intelligently identify this scenario and re-arrange the labels, however there is a reasonable workaround. The labelLines function takes the xvals argument; a list of x-values specified by the user instead of the default linear distribution across the width. So the user can decide which x-values to use for the label placement of each data series. Also, I believe this is the first answer to complete the bonus objective of aligning the labels with the curve they're on. :) label_lines.py: ``` from math import atan2,degrees import numpy as np #Label line with line2D label data def labelLine(line,x,label=None,align=True,**kwargs): ax = line.axes xdata = line.get_xdata() ydata = line.get_ydata() if (x xdata[-1]): print('x label location is outside data range!') return #Find corresponding y co-ordinate and angle of the line ip = 1 for i in range(len(xdata)): if x < xdata[i]: ip = i break y = ydata[ip-1] + (ydata[ip]-ydata[ip-1])*(x-xdata[ip-1])\/(xdata[ip]-xdata[ip-1]) if not label: label = line.get_label() if align: #Compute the slope dx = xdata[ip] - xdata[ip-1] dy = ydata[ip] - ydata[ip-1] ang = degrees(atan2(dy,dx)) #Transform to screen co-ordinates pt = np.array([x,y]).reshape((1,2)) trans_angle = ax.transData.transform_angles(np.array((ang,)),pt)[0] else: trans_angle = 0 #Set a bunch of keyword arguments if 'color' not in kwargs: kwargs['color'] = line.get_color() if ('horizontalalignment' not in kwargs) and ('ha' not in kwargs): kwargs['ha'] = 'center' if ('verticalalignment' not in kwargs) and ('va' not in kwargs): kwargs['va'] = 'center' if 'backgroundcolor' not in kwargs: kwargs['backgroundcolor'] = ax.get_facecolor() if 'clip_on' not in kwargs: kwargs['clip_on'] = True if 'zorder' not in kwargs: kwargs['zorder'] = 2.5 ax.text(x,y,label,rotation=trans_angle,**kwargs) def labelLines(lines,align=True,xvals=None,**kwargs): ax = lines[0].axes labLines = [] labels = [] #Take only the lines which have labels other than the default ones for line in lines: label = line.get_label() if \"_line\" not in label: labLines.append(line) labels.append(label) if xvals is None: xmin,xmax = ax.get_xlim() xvals = np.linspace(xmin,xmax,len(labLines)+2)[1:-1] for line,x,label in zip(labLines,xvals,labels): labelLine(line,x,label,align,**kwargs) ``` Test code to generate the pretty picture above: ``` from matplotlib import pyplot as plt from scipy.stats import loglaplace,chi2 from labellines import * X = np.linspace(0,1,500) A = [1,2,5,10,20] funcs = [np.arctan,np.sin,loglaplace(4).pdf,chi2(5).pdf] plt.subplot(221) for a in A: plt.plot(X,np.arctan(a*X),label=str(a)) labelLines(plt.gca().get_lines(),zorder=2.5) plt.subplot(222) for a in A: plt.plot(X,np.sin(a*X),label=str(a)) labelLines(plt.gca().get_lines(),align=False,fontsize=14) plt.subplot(223) for a in A: plt.plot(X,loglaplace(4).pdf(a*X),label=str(a)) xvals = [0.8,0.55,0.22,0.104,0.045] labelLines(plt.gca().get_lines(),align=False,xvals=xvals,color='k') plt.subplot(224) for a in A: plt.plot(X,chi2(5).pdf(a*X),label=str(a)) lines = plt.gca().get_lines() l1=lines[-1] labelLine(l1,0.6,label=r'$Re=${}'.format(l1.get_label()),ha='left',va='bottom',align = False) labelLines(lines[:-1],align=False) plt.show() ```",805 "best_answers_score":0.8,806 "library_name":"matplotlib",807 "question_url":"https:\/\/stackoverflow.com\/questions\/16992038\/how-to-place-inline-labels-in-a-line-plot",808 "best_answers_votes":138,809 "question_length":1022,810 "response_length":5419811 },812 {813 "question":"Ubuntu running `pip install` gives error 'The following required packages can not be built: * freetype' When performing pip install -r requirements.txt, I get the following error during the stage where it is installing matplotlib: ``` REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [not found. pip may install it below.] dateutil: yes [dateutil was not found. It is required for date axis support. pip\/easy_install may attempt to install it after matplotlib.] tornado: yes [tornado was not found. It is required for the WebAgg backend. pip\/easy_install may attempt to install it after matplotlib.] pyparsing: yes [pyparsing was not found. It is required for mathtext support. pip\/easy_install may attempt to install it after matplotlib.] pycxx: yes [Couldn't import. Using local copy.] libagg: yes [pkg-config information for 'libagg' could not be found. Using local copy.] freetype: no [pkg-config information for 'freetype2' could not be found.] ``` ... ``` The following required packages can not be built: * freetype ``` Shouldn't pip install -r requirements.txt also install freetype? How should freetype be installed in Ubuntu 12.04 so it works with matplotlib?",814 "response":"No. pip will not install system-level dependencies. This means pip will not install RPM(s) (Redhat based systems) or DEB(s) (Debian based systems). To install system dependencies you will need to use one of the following methods depending on your system. Ubuntu\/Debian: ``` apt-get install libfreetype6-dev ``` To search for packages on Ubuntu\/Debian based systems: ``` apt-cache search ``` e.g: ``` apt-cache search freetype | grep dev ``` Redhat\/CentOS\/Fedora: ``` yum -y install freetype-devel ``` To search for packages on Redhat\/CentOS\/Fedora based systems: ``` yum search ``` e.g: ``` yum search freetype | grep devel ``` Mac OS X: (via Homebrew) ``` brew install freetype ``` To search for packages on Mac OS X based systems: ``` brew search ``` e.g: ``` brew search freetype ```",815 "best_answers_score":0.8,816 "library_name":"matplotlib",817 "question_url":"https:\/\/stackoverflow.com\/questions\/20533426\/ubuntu-running-pip-install-gives-error-the-following-required-packages-can-no",818 "best_answers_votes":232,819 "question_length":1168,820 "response_length":789821 },822 {823 "question":"How to display multiple images in one figure [duplicate] This question already has answers here: Multiple figures in a single window (7 answers) Closed 7 years ago. I am trying to display 20 random images on a single Figure. The images are indeed displayed, but they are overlaid. I am using: ``` import numpy as np import matplotlib.pyplot as plt w=10 h=10 fig=plt.figure() for i in range(1,20): img = np.random.randint(10, size=(h,w)) fig.add_subplot(i,2,1) plt.imshow(img) plt.show() ``` I would like them to appear naturally in a grid layout (say 4x5), each with the same size. Part of the problem is that I do not know what the arguments to add_subplot mean. The documentation states that the arguments are the number of rows, number of columns, and plot number. There is no positioning argument. Additionally, the plot number can only be 1 or 2. How can I achieve this?",824 "response":"Here is my approach that you may try: ``` import numpy as np import matplotlib.pyplot as plt w = 10 h = 10 fig = plt.figure(figsize=(8, 8)) columns = 4 rows = 5 for i in range(1, columns*rows +1): img = np.random.randint(10, size=(h,w)) fig.add_subplot(rows, columns, i) plt.imshow(img) plt.show() ``` The resulting image: (Original answer date: Oct 7 '17 at 4:20) Edit 1 Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:- access to individual axes of subplots possibility to plot more features on selected axes\/subplot New code: ``` import numpy as np import matplotlib.pyplot as plt w = 10 h = 10 fig = plt.figure(figsize=(9, 13)) columns = 4 rows = 5 # prep (x,y) for extra plotting xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi ys = np.abs(np.sin(xs)) # absolute of sine # ax enables access to manipulate each of subplots ax = [] for i in range(columns*rows): img = np.random.randint(10, size=(h,w)) # create subplot and append to ax ax.append( fig.add_subplot(rows, columns, i+1) ) ax[-1].set_title(\"ax:\"+str(i)) # set title plt.imshow(img, alpha=0.25) # do extra plots on selected axes\/subplots # note: index starts with 0 ax[2].plot(xs, 3*ys) ax[19].plot(ys**2, xs) plt.show() # finally, render the plot ``` The resulting plot: Edit 2 In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows\/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots. ``` import matplotlib.pyplot as plt import numpy as np # settings h, w = 10, 10 # for raster image nrows, ncols = 5, 4 # array of sub-plots figsize = [6, 8] # figure size, inches # prep (x,y) for extra plotting on selected sub-plots xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi ys = np.abs(np.sin(xs)) # absolute of sine # create figure (fig), and array of axes (ax) fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize) # plot simple raster image on each sub-plot for i, axi in enumerate(ax.flat): # i runs from 0 to (nrows*ncols-1) # axi is equivalent with ax[rowid][colid] img = np.random.randint(10, size=(h,w)) axi.imshow(img, alpha=0.25) # get indices of row\/column rowid = i \/\/ ncols colid = i % ncols # write row\/col indices as axes' title for identification axi.set_title(\"Row:\"+str(rowid)+\", Col:\"+str(colid)) # one can access the axes by ax[row_id][col_id] # do additional plotting on ax[row_id][col_id] of your choice ax[0][2].plot(xs, 3*ys, color='red', linewidth=3) ax[4][3].plot(ys**2, xs, color='green', linewidth=3) plt.tight_layout(True) plt.show() ``` The resulting plot: Ticks and Tick-labels for Array of Subplots Some of the ticks and tick-labels accompanying the subplots can be hidden to get cleaner plot if all of the subplots share the same value ranges. All of the ticks and tick-labels can be hidden except for the outside edges on the left and bottom like this plot. To achieve the plot with only shared tick-labels on the left and bottom edges, you can do the following:- Add options sharex=True, sharey=True in fig, ax = plt.subplots() That line of code will become: ``` fig,ax=plt.subplots(nrows=nrows,ncols=ncols,figsize=figsize,sharex=True,sharey=True) ``` To specify required number of ticks, and labels to plot, inside the body of for i, axi in enumerate(ax.flat):, add these code ``` axi.xaxis.set_major_locator(plt.MaxNLocator(5)) axi.yaxis.set_major_locator(plt.MaxNLocator(4)) ``` the number 5, and 4 are the number of ticks\/tick_labels to plot. You may need other values that suit your plots.",825 "best_answers_score":0.8,826 "library_name":"matplotlib",827 "question_url":"https:\/\/stackoverflow.com\/questions\/46615554\/how-to-display-multiple-images-in-one-figure",828 "best_answers_votes":332,829 "question_length":875,830 "response_length":3822831 },832 {833 "question":"plot different color for different categorical levels I have this data frame diamonds which is composed of variables like (carat, price, color), and I want to draw a scatter plot of price to carat for each color, which means different color has different color in the plot. This is easy in R with ggplot: ``` ggplot(aes(x=carat, y=price, color=color), #by setting color=color, ggplot automatically draw in different colors data=diamonds) + geom_point(stat='summary', fun.y=median) ``` I wonder how could this be done in Python using matplotlib ? PS: I know about auxiliary plotting packages, such as seaborn and ggplot for python, and I don't prefer them, just want to find out if it is possible to do the job using matplotlib alone, ;P",834 "response":"Imports and Sample DataFrame ```py import matplotlib.pyplot as plt import pandas as pd import seaborn as sns # for sample data from matplotlib.lines import Line2D # for legend handle # DataFrame used for all options df = sns.load_dataset('diamonds') carat cut color clarity depth table price x y z 0 0.23 Ideal E SI2 61.5 55.0 326 3.95 3.98 2.43 1 0.21 Premium E SI1 59.8 61.0 326 3.89 3.84 2.31 2 0.23 Good E VS1 56.9 65.0 327 4.05 4.07 2.31 ``` With matplotlib You can pass plt.scatter a c argument, which allows you to select the colors. The following code defines a colors dictionary to map the diamond colors to the plotting colors. ```py fig, ax = plt.subplots(figsize=(6, 6)) colors = {'D':'tab:blue', 'E':'tab:orange', 'F':'tab:green', 'G':'tab:red', 'H':'tab:purple', 'I':'tab:brown', 'J':'tab:pink'} ax.scatter(df['carat'], df['price'], c=df['color'].map(colors)) # add a legend handles = [Line2D([0], [0], marker='o', color='w', markerfacecolor=v, label=k, markersize=8) for k, v in colors.items()] ax.legend(title='color', handles=handles, bbox_to_anchor=(1.05, 1), loc='upper left') plt.show() ``` df['color'].map(colors) effectively maps the colors from \"diamond\" to \"plotting\". (Forgive me for not putting another example image up, I think 2 is enough :P) With seaborn You can use seaborn which is a wrapper around matplotlib that makes it look prettier by default (rather opinion-based, I know :P) but also adds some plotting functions. For this you could use seaborn.lmplot with fit_reg=False (which prevents it from automatically doing some regression). sns.scatterplot(x='carat', y='price', data=df, hue='color', ec=None) also does the same thing. Selecting hue='color' tells seaborn to split and plot the data based on the unique values in the 'color' column. ```py sns.lmplot(x='carat', y='price', data=df, hue='color', fit_reg=False) ``` With pandas.DataFrame.groupby & pandas.DataFrame.plot If you don't want to use seaborn, use pandas.groupby to get the colors alone, and then plot them using just matplotlib, but you'll have to manually assign colors as you go, I've added an example below: ```py fig, ax = plt.subplots(figsize=(6, 6)) grouped = df.groupby('color') for key, group in grouped: group.plot(ax=ax, kind='scatter', x='carat', y='price', label=key, color=colors[key]) plt.show() ``` This code assumes the same DataFrame as above, and then groups it based on color. It then iterates over these groups, plotting for each one. To select a color, I've created a colors dictionary, which can map the diamond color (for instance D) to a real color (for instance tab:blue).",835 "best_answers_score":0.8,836 "library_name":"matplotlib",837 "question_url":"https:\/\/stackoverflow.com\/questions\/26139423\/plot-different-color-for-different-categorical-levels",838 "best_answers_votes":227,839 "question_length":736,840 "response_length":2602841 },842 {843 "question":"Can Pandas plot a histogram of dates? I've taken my Series and coerced it to a datetime column of dtype=datetime64[ns] (though only need day resolution...not sure how to change). ``` import pandas as pd df = pd.read_csv('somefile.csv') column = df['date'] column = pd.to_datetime(column, coerce=True) ``` but plotting doesn't work: ``` ipdb> column.plot(kind='hist') *** TypeError: ufunc add cannot use operands with types dtype('<M8[ns]') and dtype('float64') ``` I'd like to plot a histogram that just shows the count of dates by week, month, or year. Surely there is a way to do this in pandas?",844 "response":"Given this df: ``` date 0 2001-08-10 1 2002-08-31 2 2003-08-29 3 2006-06-21 4 2002-03-27 5 2003-07-14 6 2004-06-15 7 2003-08-14 8 2003-07-29 ``` and, if it's not already the case: ``` df[\"date\"] = df[\"date\"].astype(\"datetime64\") ``` To show the count of dates by month: ``` df.groupby(df[\"date\"].dt.month).count().plot(kind=\"bar\") ``` .dt allows you to access the datetime properties. Which will give you: You can replace month by year, day, etc.. If you want to distinguish year and month for instance, just do: ``` df.groupby([df[\"date\"].dt.year, df[\"date\"].dt.month]).count().plot(kind=\"bar\") ``` Which gives:",845 "best_answers_score":0.8,846 "library_name":"matplotlib",847 "question_url":"https:\/\/stackoverflow.com\/questions\/27365467\/can-pandas-plot-a-histogram-of-dates",848 "best_answers_votes":232,849 "question_length":597,850 "response_length":612851 },852 {853 "question":"How to make a 3D scatter plot I am currently have a nx3 matrix array. I want plot the three columns as three axis's. How can I do that? I have googled and people suggested using Matlab, but I am really having a hard time with understanding it. I also need it be a scatter plot.",854 "response":"You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want. ```py import matplotlib.pyplot as plt import random fig = plt.figure(figsize=(12, 12)) ax = fig.add_subplot(projection='3d') sequence_containing_x_vals = list(range(0, 100)) sequence_containing_y_vals = list(range(0, 100)) sequence_containing_z_vals = list(range(0, 100)) random.shuffle(sequence_containing_x_vals) random.shuffle(sequence_containing_y_vals) random.shuffle(sequence_containing_z_vals) ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals) plt.show() ``` The code above generates a figure like:",855 "best_answers_score":0.8,856 "library_name":"matplotlib",857 "question_url":"https:\/\/stackoverflow.com\/questions\/1985856\/how-to-make-a-3d-scatter-plot",858 "best_answers_votes":230,859 "question_length":277,860 "response_length":651861 },862 {863 "question":"Pandas plot doesn't show When using this in a script (not IPython), nothing happens, i.e. the plot window doesn't appear : ``` import numpy as np import pandas as pd ts = pd.Series(np.random.randn(1000), index=pd.date_range('1\/1\/2000', periods=1000)) ts.plot() ``` Even when adding time.sleep(5), there is still nothing. Why? Is there a way to do it, without having to manually call matplotlib ?",864 "response":"Once you have made your plot, you need to tell matplotlib to show it. The usual way to do things is to import matplotlib.pyplot and call show from there: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt ts = pd.Series(np.random.randn(1000), index=pd.date_range('1\/1\/2000', periods=1000)) ts.plot() plt.show() ``` In older versions of pandas, you were able to find a backdoor to matplotlib, as in the example below. NOTE: This no longer works in modern versions of pandas, and I still recommend importing matplotlib separately, as in the example above. ``` import numpy as np import pandas as pd ts = pd.Series(np.random.randn(1000), index=pd.date_range('1\/1\/2000', periods=1000)) ts.plot() pd.tseries.plotting.pylab.show() ``` But all you are doing there is finding somewhere that matplotlib has been imported in pandas, and calling the same show function from there. Are you trying to avoid calling matplotlib in an effort to speed things up? If so then you are really not speeding anything up, since pandas already imports pyplot: ``` python -mtimeit -s 'import pandas as pd' 100000000 loops, best of 3: 0.0122 usec per loop python -mtimeit -s 'import pandas as pd; import matplotlib.pyplot as plt' 100000000 loops, best of 3: 0.0125 usec per loop ``` Finally, the reason the example you linked in comments doesn't need the call to matplotlib is because it is being run interactively in an iPython notebook, not in a script.",865 "best_answers_score":0.8,866 "library_name":"matplotlib",867 "question_url":"https:\/\/stackoverflow.com\/questions\/34347145\/pandas-plot-doesnt-show",868 "best_answers_votes":241,869 "question_length":395,870 "response_length":1452871 },872 {873 "question":"Matplotlib figure facecolor (background color) Can someone please explain why the code below does not work when setting the facecolor of the figure? ``` import matplotlib.pyplot as plt # create figure instance fig1 = plt.figure(1) fig1.set_figheight(11) fig1.set_figwidth(8.5) rect = fig1.patch rect.set_facecolor('red') # works with plt.show(). # Does not work with plt.savefig(\"trial_fig.png\") ax = fig1.add_subplot(1,1,1) x = 1, 2, 3 y = 1, 4, 9 ax.plot(x, y) # plt.show() # Will show red face color set above using rect.set_facecolor('red') plt.savefig(\"trial_fig.png\") # The saved trial_fig.png DOES NOT have the red facecolor. # plt.savefig(\"trial_fig.png\", facecolor='red') # Here the facecolor is red. ``` When I specify the height and width of the figure using fig1.set_figheight(11) fig1.set_figwidth(8.5) these are picked up by the command plt.savefig(\"trial_fig.png\"). However, the facecolor setting is not picked up. Why? Thanks for your help.",874 "response":"It's because savefig overrides the facecolor for the background of the figure. (This is deliberate, actually... The assumption is that you'd probably want to control the background color of the saved figure with the facecolor kwarg to savefig. It's a confusing and inconsistent default, though!) The easiest workaround is just to do fig.savefig('whatever.png', facecolor=fig.get_facecolor(), edgecolor='none') (I'm specifying the edgecolor here because the default edgecolor for the actual figure is white, which will give you a white border around the saved figure)",875 "best_answers_score":0.8,876 "library_name":"matplotlib",877 "question_url":"https:\/\/stackoverflow.com\/questions\/4804005\/matplotlib-figure-facecolor-background-color",878 "best_answers_votes":197,879 "question_length":956,880 "response_length":566881 },882 {883 "question":"First and last row cut in half of heatmap plot When plotting heatmaps with seaborn (and correlation matrices with matplotlib) the first and the last row is cut in halve. This happens also when I run this minimal code example which I found online. ```py import pandas as pd import seaborn as sns import matplotlib.pyplot as plt data = pd.read_csv('https:\/\/raw.githubusercontent.com\/resbaz\/r-novice-gapminder-files\/master\/data\/gapminder-FiveYearData.csv') plt.figure(figsize=(10,5)) sns.heatmap(data.corr()) plt.show() ``` The labels at the y axis are on the correct spot, but the rows aren't completely there. A few days ago, it work as intended. Since then, I installed texlive-xetex so I removed it again but it didn't solve my problem. Any ideas what I could be missing?",884 "response":"Unfortunately matplotlib 3.1.1 broke seaborn heatmaps; and in general inverted axes with fixed ticks. This is fixed in the current development version; you may hence revert to matplotlib 3.1.0 use matplotlib 3.1.2 or higher set the heatmap limits manually (ax.set_ylim(bottom, top) # set the ylim to bottom, top)",885 "best_answers_score":0.8,886 "library_name":"matplotlib",887 "question_url":"https:\/\/stackoverflow.com\/questions\/56942670\/first-and-last-row-cut-in-half-of-heatmap-plot",888 "best_answers_votes":122,889 "question_length":772,890 "response_length":312891 },892 {893 "question":"What is the difference between 'log' and 'symlog'? In matplotlib, I can set the axis scaling using either pyplot.xscale() or Axes.set_xscale(). Both functions accept three different scales: 'linear' | 'log' | 'symlog'. What is the difference between 'log' and 'symlog'? In a simple test I did, they both looked exactly the same. I know the documentation says they accept different parameters, but I still don't understand the difference between them. Can someone please explain it? The answer will be the best if it has some sample code and graphics! (also: where does the name 'symlog' come from?)",894 "response":"I finally found some time to do some experiments in order to understand the difference between them. Here's what I discovered: log only allows positive values, and lets you choose how to handle negative ones (mask or clip). symlog means symmetrical log, and allows positive and negative values. symlog allows to set a range around zero within the plot will be linear instead of logarithmic. I think everything will get a lot easier to understand with graphics and examples, so let's try them: ``` import numpy from matplotlib import pyplot # Enable interactive mode pyplot.ion() # Draw the grid lines pyplot.grid(True) # Numbers from -50 to 50, with 0.1 as step xdomain = numpy.arange(-50,50, 0.1) # Plots a simple linear function 'f(x) = x' pyplot.plot(xdomain, xdomain) # Plots 'sin(x)' pyplot.plot(xdomain, numpy.sin(xdomain)) # 'linear' is the default mode, so this next line is redundant: pyplot.xscale('linear') ``` ``` # How to treat negative values? # 'mask' will treat negative values as invalid # 'mask' is the default, so the next two lines are equivalent pyplot.xscale('log') pyplot.xscale('log', nonposx='mask') ``` ``` # 'clip' will map all negative values a very small positive one pyplot.xscale('log', nonposx='clip') ``` ``` # 'symlog' scaling, however, handles negative values nicely pyplot.xscale('symlog') ``` ``` # And you can even set a linear range around zero pyplot.xscale('symlog', linthreshx=20) ``` Just for completeness, I've used the following code to save each figure: ``` # Default dpi is 80 pyplot.savefig('matplotlib_xscale_linear.png', dpi=50, bbox_inches='tight') ``` Remember you can change the figure size using: ``` fig = pyplot.gcf() fig.set_size_inches([4., 3.]) # Default size: [8., 6.] ``` (If you are unsure about me answering my own question, read this)",895 "best_answers_score":0.8,896 "library_name":"matplotlib",897 "question_url":"https:\/\/stackoverflow.com\/questions\/3305865\/what-is-the-difference-between-log-and-symlog",898 "best_answers_votes":245,899 "question_length":598,900 "response_length":1798901 },902 {903 "question":"ValueError: Unknown projection '3d' I just installed matplotlib and am trying to run one of there example scripts. However I run into the error detailed below. What am I doing wrong? ``` from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection='3d') X, Y, Z = axes3d.get_test_data(0.05) cset = ax.contour(X, Y, Z, 16, extend3d=True) ax.clabel(cset, fontsize=9, inline=1) plt.show() ``` The error is ``` Traceback (most recent call last): File \"\", line 245, in run_nodebug File \"\", line 5, in File \"C:\\Python26\\lib\\site-packages\\matplotlib\\figure.py\", line 945, in gca return self.add_subplot(111, **kwargs) File \"C:\\Python26\\lib\\site-packages\\matplotlib\\figure.py\", line 677, in add_subplot projection_class = get_projection_class(projection) File \"C:\\Python26\\lib\\site-packages\\matplotlib\\projections\\__init__.py\", line 61, in get_projection_class raise ValueError(\"Unknown projection '%s'\" % projection) ValueError: Unknown projection '3d' ```",904 "response":"First off, I think mplot3D worked a bit differently in matplotlib version 0.99 than it does in the current version of matplotlib. Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib.\"__version__\") I'm guessing you're running version 0.99, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib. If you're running version 0.99, try doing this instead of using using the projection keyword argument: ``` import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization! fig = plt.figure() ax = Axes3D(fig) #<-- Note the difference from your original code... X, Y, Z = axes3d.get_test_data(0.05) cset = ax.contour(X, Y, Z, 16, extend3d=True) ax.clabel(cset, fontsize=9, inline=1) plt.show() ``` This should work in matplotlib 1.0.x, as well, not just 0.99.",905 "best_answers_score":0.8,906 "library_name":"matplotlib",907 "question_url":"https:\/\/stackoverflow.com\/questions\/3810865\/valueerror-unknown-projection-3d",908 "best_answers_votes":121,909 "question_length":1004,910 "response_length":897911 },912 {913 "question":"matplotlib colorbar for scatter I'm working with data that has the data has 3 plotting parameters: x,y,c. How do you create a custom color value for a scatter plot? Extending this example I'm trying to do: ``` import matplotlib import matplotlib.pyplot as plt cm = matplotlib.cm.get_cmap('RdYlBu') colors=[cm(1.*i\/20) for i in range(20)] xy = range(20) plt.subplot(111) colorlist=[colors[x\/2] for x in xy] #actually some other non-linear relationship plt.scatter(xy, xy, c=colorlist, s=35, vmin=0, vmax=20) plt.colorbar() plt.show() ``` but the result is TypeError: You must first set_array for mappable",914 "response":"From the matplotlib docs on scatter 1: cmap is only used if c is an array of floats So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin\/vmax get the colors of the endpoints. How does this work for you? ``` import matplotlib.pyplot as plt cm = plt.cm.get_cmap('RdYlBu') xy = range(20) z = xy sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm) plt.colorbar(sc) plt.show() ```",915 "best_answers_score":0.8,916 "library_name":"matplotlib",917 "question_url":"https:\/\/stackoverflow.com\/questions\/6063876\/matplotlib-colorbar-for-scatter",918 "best_answers_votes":264,919 "question_length":603,920 "response_length":597921 },922 {923 "question":"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 \"\", line 1, in 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 ```",924 "response":"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.",925 "best_answers_score":0.8,926 "library_name":"matplotlib",927 "question_url":"https:\/\/stackoverflow.com\/questions\/16010869\/plot-a-bar-using-matplotlib-using-a-dictionary",928 "best_answers_votes":208,929 "question_length":1385,930 "response_length":609931 },932 {933 "question":"OpenCV giving wrong color to colored images on loading I'm loading in a color image in Python OpenCV and plotting the same. However, the image I get has it's colors all mixed up. Here is the code: ``` import cv2 import numpy as np from numpy import array, arange, uint8 from matplotlib import pyplot as plt img = cv2.imread('lena_caption.png', cv2.IMREAD_COLOR) bw_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) images = [] images.append(img) images.append(bw_img) titles = ['Original Image','BW Image'] for i in xrange(len(images)): plt.subplot(1,2,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([]) plt.show() ``` Here is the original image: And here is the plotted image:",934 "response":"OpenCV uses BGR as its default colour order for images, matplotlib uses RGB. When you display an image loaded with OpenCv in matplotlib the channels will be back to front. The easiest way of fixing this is to use OpenCV to explicitly convert it back to RGB, much like you do when creating the greyscale image. ``` RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) ``` And then use that in your plot.",935 "best_answers_score":0.8,936 "library_name":"matplotlib",937 "question_url":"https:\/\/stackoverflow.com\/questions\/39316447\/opencv-giving-wrong-color-to-colored-images-on-loading",938 "best_answers_votes":258,939 "question_length":705,940 "response_length":396941 },942 {943 "question":"plot with custom text for x axis points I am drawing a plot using matplotlib and python like the sample code below. ``` x = array([0,1,2,3]) y = array([20,21,22,23]) plot(x,y) show() ``` As it is the code above on the x axis I will see drawn values 0.0, 0.5, 1.0, 1.5 i.e. the same values of my reference x values. Is there anyway to map each point of x to a different string? So for example I want x axis to show months names( strings Jun, July,...) or other strings like people names ( \"John\", \"Arnold\", ... ) or clock time ( \"12:20\", \"12:21\", \"12:22\", .. ). Do you know what I can do or what function to have a look at? For my purpose could it be matplotlib.ticker of help?",944 "response":"You can manually set xticks (and yticks) using pyplot.xticks: ``` import matplotlib.pyplot as plt import numpy as np x = np.array([0,1,2,3]) y = np.array([20,21,22,23]) my_xticks = ['John','Arnold','Mavis','Matt'] plt.xticks(x, my_xticks) plt.plot(x, y) plt.show() ```",945 "best_answers_score":0.8,946 "library_name":"matplotlib",947 "question_url":"https:\/\/stackoverflow.com\/questions\/3100985\/plot-with-custom-text-for-x-axis-points",948 "best_answers_votes":260,949 "question_length":676,950 "response_length":268951 },952 {953 "question":"Scatter plot and Color mapping in Python I have a range of points x and y stored in numpy arrays. Those represent x(t) and y(t) where t=0...T-1 I am plotting a scatter plot using ``` import matplotlib.pyplot as plt plt.scatter(x,y) plt.show() ``` I would like to have a colormap representing the time (therefore coloring the points depending on the index in the numpy arrays) What is the easiest way to do so?",954 "response":"Here is an example ``` import numpy as np import matplotlib.pyplot as plt x = np.random.rand(100) y = np.random.rand(100) t = np.arange(100) plt.scatter(x, y, c=t) plt.show() ``` Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100]. Perhaps an easier-to-understand example is the slightly simpler ``` import numpy as np import matplotlib.pyplot as plt x = np.arange(100) y = x t = x plt.scatter(x, y, c=t) plt.show() ``` Note that the array you pass as c doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum\/maximum values in c correspond to the bottom\/top of the colormap. Colormaps You can change the colormap by adding ``` import matplotlib.cm as cm plt.scatter(x, y, c=t, cmap=cm.cmap_name) ``` Importing matplotlib.cm is optional as you can call colormaps as cmap=\"cmap_name\" just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r. So either ``` plt.scatter(x, y, c=t, cmap=cm.cmap_name_r) # or plt.scatter(x, y, c=t, cmap=\"cmap_name_r\") ``` will work. Examples are \"jet_r\" or cm.plasma_r. Here's an example with the new 1.5 colormap viridis: ``` import numpy as np import matplotlib.pyplot as plt x = np.arange(100) y = x t = x fig, (ax1, ax2) = plt.subplots(1, 2) ax1.scatter(x, y, c=t, cmap='viridis') ax2.scatter(x, y, c=t, cmap='viridis_r') plt.show() ``` Colorbars You can add a colorbar by using ``` plt.scatter(x, y, c=t, cmap='viridis') plt.colorbar() plt.show() ``` Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots() or ax = fig.add_subplot(111)), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.",955 "best_answers_score":0.8,956 "library_name":"matplotlib",957 "question_url":"https:\/\/stackoverflow.com\/questions\/17682216\/scatter-plot-and-color-mapping-in-python",958 "best_answers_votes":241,959 "question_length":409,960 "response_length":1928961 },962 {963 "question":"How can I get the output of a matplotlib plot as an SVG? I need to take the output of a matplotlib plot and turn it into an SVG path that I can use on a laser cutter. ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(0,100,0.00001) y = x*np.sin(2*pi*x) plt.plot(y) plt.show() ``` For example, below you see a waveform. I would like to be able to output or save this waveform as an SVG path that I can later work with in a program such as Adobe Illustrator. I am aware of an SVG library called \"Cairo\" that matplotlib can use (matplotlib.use('Cairo')), however it's not clear to me that this will give me access to the SVG path that I need, even though matplotlib will now be using Cairo to generate the plot. I do have cairo working on my system, and can successfully draw an example composed of SVG paths that I can indeed edit in Illustrator, but I don't have a way to take my equation above into an SVG path. ``` import cairo from cairo import SVGSurface, Context, Matrix s = SVGSurface('example1.svg', WIDTH, HEIGHT) c = Context(s) # Transform to normal cartesian coordinate system m = Matrix(yy=-1, y0=HEIGHT) c.transform(m) # Set a background color c.save() c.set_source_rgb(0.3, 0.3, 1.0) c.paint() c.restore() # Draw some lines c.move_to(0, 0) c.line_to(2 * 72, 2* 72) c.line_to(3 * 72, 1 * 72) c.line_to(4 * 72, 2 * 72) c.line_to(6 * 72, 0) c.close_path() c.save() c.set_line_width(6.0) c.stroke_preserve() c.set_source_rgb(0.3, 0.3, 0.3) c.fill() c.restore() # Draw a circle c.save() c.set_line_width(6.0) c.arc(1 * 72, 3 * 72, 0.5 * 72, 0, 2 * pi) c.stroke_preserve() c.set_source_rgb(1.0, 1.0, 0) c.fill() c.restore() # Save as a SVG and PNG s.write_to_png('example1.png') s.finish() ``` (note that the image displayed here is a png, as stackoverflow doesn't accept svg graphics for display)",964 "response":"You will most probably want to fix the image size and get rid of all sorts of backgrounds and axis markers: ``` import matplotlib.pyplot as plt import numpy as np plt.figure(figsize=[6, 6]) x = np.arange(0, 100, 0.00001) y = x*np.sin(2* np.pi * x) plt.plot(y) plt.axis('off') plt.gca().set_position([0, 0, 1, 1]) plt.savefig(\"test.svg\") ``` The resulting SVG file contains only one extra element, as savefig really wants to save the figure background. The color of this background is easy to change to 'none', but it does not seem to get rid of it. Anyway, the SVG is very clean otherwise and in the correct scale (1\/72\" per unit).",965 "best_answers_score":0.8,966 "library_name":"matplotlib",967 "question_url":"https:\/\/stackoverflow.com\/questions\/24525111\/how-can-i-get-the-output-of-a-matplotlib-plot-as-an-svg",968 "best_answers_votes":139,969 "question_length":1822,970 "response_length":631971 },972 {973 "question":"why is plotting with Matplotlib so slow? I'm currently evaluating different python plotting libraries. Right now I'm trying matplotlib and I'm quite disappointed with the performance. The following example is modified from SciPy examples and gives me only ~ 8 frames per second! Any ways of speeding this up or should I pick a different plotting library? ``` from pylab import * import time ion() fig = figure() ax1 = fig.add_subplot(611) ax2 = fig.add_subplot(612) ax3 = fig.add_subplot(613) ax4 = fig.add_subplot(614) ax5 = fig.add_subplot(615) ax6 = fig.add_subplot(616) x = arange(0,2*pi,0.01) y = sin(x) line1, = ax1.plot(x, y, 'r-') line2, = ax2.plot(x, y, 'g-') line3, = ax3.plot(x, y, 'y-') line4, = ax4.plot(x, y, 'm-') line5, = ax5.plot(x, y, 'k-') line6, = ax6.plot(x, y, 'p-') # turn off interactive plotting - speeds things up by 1 Frame \/ second plt.ioff() tstart = time.time() # for profiling for i in arange(1, 200): line1.set_ydata(sin(x+i\/10.0)) # update the data line2.set_ydata(sin(2*x+i\/10.0)) line3.set_ydata(sin(3*x+i\/10.0)) line4.set_ydata(sin(4*x+i\/10.0)) line5.set_ydata(sin(5*x+i\/10.0)) line6.set_ydata(sin(6*x+i\/10.0)) draw() # redraw the canvas print 'FPS:' , 200\/(time.time()-tstart) ```",974 "response":"First off, (though this won't change the performance at all) consider cleaning up your code, similar to this: ``` import matplotlib.pyplot as plt import numpy as np import time x = np.arange(0, 2*np.pi, 0.01) y = np.sin(x) fig, axes = plt.subplots(nrows=6) styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-'] lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)] fig.show() tstart = time.time() for i in xrange(1, 20): for j, line in enumerate(lines, start=1): line.set_ydata(np.sin(j*x + i\/10.0)) fig.canvas.draw() print 'FPS:' , 20\/(time.time()-tstart) ``` With the above example, I get around 10fps. Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display. However, there are a lot of things you can do to speed this example up. There are two main reasons why this is as slow as it is. 1) Calling fig.canvas.draw() redraws everything. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc. 2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw. Both these can be fixed by using blitting. To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue. However, without knowing a bit more about what you're doing, I can't help you there. Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast. ``` import matplotlib.pyplot as plt import numpy as np import time x = np.arange(0, 2*np.pi, 0.1) y = np.sin(x) fig, axes = plt.subplots(nrows=6) fig.show() # We need to draw the canvas before we start animating... fig.canvas.draw() styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-'] def plot(ax, style): return ax.plot(x, y, style, animated=True)[0] lines = [plot(ax, style) for ax, style in zip(axes, styles)] # Let's capture the background of the figure backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes] tstart = time.time() for i in xrange(1, 2000): items = enumerate(zip(lines, axes, backgrounds), start=1) for j, (line, ax, background) in items: fig.canvas.restore_region(background) line.set_ydata(np.sin(j*x + i\/10.0)) ax.draw_artist(line) fig.canvas.blit(ax.bbox) print 'FPS:' , 2000\/(time.time()-tstart) ``` This gives me ~200fps. To make this a bit more convenient, there's an animations module in recent versions of matplotlib. As an example: ``` import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np x = np.arange(0, 2*np.pi, 0.1) y = np.sin(x) fig, axes = plt.subplots(nrows=6) styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-'] def plot(ax, style): return ax.plot(x, y, style, animated=True)[0] lines = [plot(ax, style) for ax, style in zip(axes, styles)] def animate(i): for j, line in enumerate(lines, start=1): line.set_ydata(np.sin(j*x + i\/10.0)) return lines # We'd normally specify a reasonable \"interval\" here... ani = animation.FuncAnimation(fig, animate, xrange(1, 200), interval=0, blit=True) plt.show() ```",975 "best_answers_score":0.8,976 "library_name":"matplotlib",977 "question_url":"https:\/\/stackoverflow.com\/questions\/8955869\/why-is-plotting-with-matplotlib-so-slow",978 "best_answers_votes":144,979 "question_length":1217,980 "response_length":3203981 },982 {983 "question":"Change line width of lines in matplotlib pyplot legend [duplicate] This question already has answers here: increase the linewidth of the legend lines in matplotlib (4 answers) Closed 7 years ago. I would like to change the thickness\/width of the line samples featured in the pyplot legend. Line width of line samples within legend are the same as the lines they represent in the plot (so if line y1 has linewidth=7.0, the legend's corresponding y1 label will also have linewidth=7.0). I would like the legend lines to be thicker than lines featured in the plot. For example, the following code generates the following image: ``` import numpy as np import matplotlib.pyplot as plt # make some data x = np.linspace(0, 2*np.pi) y1 = np.sin(x) y2 = np.cos(x) # plot sin(x) and cos(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y1, c='b', label='y1',linewidth=7.0) ax.plot(x, y2, c='r', label='y2') leg = plt.legend() plt.show() ``` I want to set the y1 label in the legend to have linewidth=7.0, while the y1 line featured in the plot has a different width (linewidth=1.0). Related issues had answers for changing the linewidth of the legend bounding box through leg.get_frame().set_linewidth(7.0). This does not change linewidth of the lines within the legend.",984 "response":"@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way. Method 1 ``` import numpy as np import matplotlib.pyplot as plt # make some data x = np.linspace(0, 2*np.pi) y1 = np.sin(x) y2 = np.cos(x) # plot sin(x) and cos(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y1, c='b', label='y1') ax.plot(x, y2, c='r', label='y2') leg = plt.legend() # get the individual lines inside legend and set line width for line in leg.get_lines(): line.set_linewidth(4) # get label texts inside legend and set font size for text in leg.get_texts(): text.set_fontsize('x-large') plt.savefig('leg_example') plt.show() ``` Method 2 ``` import numpy as np import matplotlib.pyplot as plt # make some data x = np.linspace(0, 2*np.pi) y1 = np.sin(x) y2 = np.cos(x) # plot sin(x) and cos(x) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(x, y1, c='b', label='y1') ax.plot(x, y2, c='r', label='y2') leg = plt.legend() # get the lines and texts inside legend box leg_lines = leg.get_lines() leg_texts = leg.get_texts() # bulk-set the properties of all lines and texts plt.setp(leg_lines, linewidth=4) plt.setp(leg_texts, fontsize='x-large') plt.savefig('leg_example') plt.show() ``` The above two methods produce the same output image:",985 "best_answers_score":0.8,986 "library_name":"matplotlib",987 "question_url":"https:\/\/stackoverflow.com\/questions\/42758897\/change-line-width-of-lines-in-matplotlib-pyplot-legend",988 "best_answers_votes":66,989 "question_length":1270,990 "response_length":1560991 },992 {993 "question":"Change figure window title in pylab How can I set a figure window's title in pylab\/python? ``` fig = figure(9) # 9 is now the title of the window fig.set_title(\"Test\") #doesn't work fig.title = \"Test\" #doesn't work ```",994 "response":"If you want to actually change the window you can do: ``` fig = pylab.gcf() fig.canvas.manager.set_window_title('Test') ```",995 "best_answers_score":0.8,996 "library_name":"matplotlib",997 "question_url":"https:\/\/stackoverflow.com\/questions\/5812960\/change-figure-window-title-in-pylab",998 "best_answers_votes":185,999 "question_length":218,1000 "response_length":1231001 },1002 {1003 "question":"Plotting with seaborn using the matplotlib object-oriented interface I strongly prefer using matplotlib in OOP style: ``` f, axarr = plt.subplots(2, sharex=True) axarr[0].plot(...) axarr[1].plot(...) ``` This makes it easier to keep track of multiple figures and subplots. Question: How to use seaborn this way? Or, how to change this example to OOP style? How to tell seaborn plotting functions like lmplot which Figure or Axes it plots to?",1004 "response":"It depends a bit on which seaborn function you are using. The plotting functions in seaborn are broadly divided into two types: \"Axes-level\" functions, including regplot, boxplot, kdeplot, and many others \"Figure-level\" functions, including relplot, catplot, displot, pairplot, jointplot and one or two others The first group is identified by taking an explicit ax argument and returning an Axes object. As this suggests, you can use them in an \"object oriented\" style by passing your Axes to them: ``` f, (ax1, ax2) = plt.subplots(2) sns.regplot(x, y, ax=ax1) sns.kdeplot(x, ax=ax2) ``` Axes-level functions will only draw onto an Axes and won't otherwise mess with the figure, so they can coexist perfectly happily in an object-oriented matplotlib script. The second group of functions (Figure-level) are distinguished by the fact that the resulting plot can potentially include several Axes which are always organized in a \"meaningful\" way. That means that the functions need to have total control over the figure, so it isn't possible to plot, say, an lmplot onto one that already exists. Calling the function always initializes a figure and sets it up for the specific plot it's drawing. However, once you've called lmplot, it will return an object of the type FacetGrid. This object has some methods for operating on the resulting plot that know a bit about the structure of the plot. It also exposes the underlying figure and array of axes at the FacetGrid.fig and FacetGrid.axes arguments. The jointplot function is very similar, but it uses a JointGrid object. So you can still use these functions in an object-oriented context, but all of your customization has to come after you've called the function.",1005 "best_answers_score":0.8,1006 "library_name":"matplotlib",1007 "question_url":"https:\/\/stackoverflow.com\/questions\/23969619\/plotting-with-seaborn-using-the-matplotlib-object-oriented-interface",1008 "best_answers_votes":298,1009 "question_length":441,1010 "response_length":17131011 },1012 {1013 "question":"Defining the midpoint of a colormap in matplotlib I want to set the middle point of a colormap, i.e., my data goes from -5 to 10 and I want zero to be the middle point. I think the way to do it is by subclassing normalize and using the norm, but I didn't find any example and it is not clear to me, what exactly have I to implement?",1014 "response":"I know this is late to the game, but I just went through this process and came up with a solution that perhaps less robust than subclassing normalize, but much simpler. I thought it'd be good to share it here for posterity. The function ``` import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import AxesGrid def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the \"center\" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap's dynamic range to be at zero. Input ----- cmap : The matplotlib colormap to be altered start : Offset from lowest point in the colormap's range. Defaults to 0.0 (no lower offset). Should be between 0.0 and `midpoint`. midpoint : The new center of the colormap. Defaults to 0.5 (no shift). Should be between 0.0 and 1.0. In general, this should be 1 - vmax \/ (vmax + abs(vmin)) For example if your data range from -15.0 to +5.0 and you want the center of the colormap at 0.0, `midpoint` should be set to 1 - 5\/(5 + 15)) or 0.75 stop : Offset from highest point in the colormap's range. Defaults to 1.0 (no upper offset). Should be between `midpoint` and 1.0. ''' cdict = { 'red': [], 'green': [], 'blue': [], 'alpha': [] } # regular index to compute the colors reg_index = np.linspace(start, stop, 257) # shifted index to match the data shift_index = np.hstack([ np.linspace(0.0, midpoint, 128, endpoint=False), np.linspace(midpoint, 1.0, 129, endpoint=True) ]) for ri, si in zip(reg_index, shift_index): r, g, b, a = cmap(ri) cdict['red'].append((si, r, r)) cdict['green'].append((si, g, g)) cdict['blue'].append((si, b, b)) cdict['alpha'].append((si, a, a)) newcmap = matplotlib.colors.LinearSegmentedColormap(name, cdict) plt.register_cmap(cmap=newcmap) return newcmap ``` An example ``` biased_data = np.random.random_integers(low=-15, high=5, size=(37,37)) orig_cmap = matplotlib.cm.coolwarm shifted_cmap = shiftedColorMap(orig_cmap, midpoint=0.75, name='shifted') shrunk_cmap = shiftedColorMap(orig_cmap, start=0.15, midpoint=0.75, stop=0.85, name='shrunk') fig = plt.figure(figsize=(6,6)) grid = AxesGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=0.5, label_mode=\"1\", share_all=True, cbar_location=\"right\", cbar_mode=\"each\", cbar_size=\"7%\", cbar_pad=\"2%\") # normal cmap im0 = grid[0].imshow(biased_data, interpolation=\"none\", cmap=orig_cmap) grid.cbar_axes[0].colorbar(im0) grid[0].set_title('Default behavior (hard to see bias)', fontsize=8) im1 = grid[1].imshow(biased_data, interpolation=\"none\", cmap=orig_cmap, vmax=15, vmin=-15) grid.cbar_axes[1].colorbar(im1) grid[1].set_title('Centered zero manually,\\nbut lost upper end of dynamic range', fontsize=8) im2 = grid[2].imshow(biased_data, interpolation=\"none\", cmap=shifted_cmap) grid.cbar_axes[2].colorbar(im2) grid[2].set_title('Recentered cmap with function', fontsize=8) im3 = grid[3].imshow(biased_data, interpolation=\"none\", cmap=shrunk_cmap) grid.cbar_axes[3].colorbar(im3) grid[3].set_title('Recentered cmap with function\\nand shrunk range', fontsize=8) for ax in grid: ax.set_yticks([]) ax.set_xticks([]) ``` Results of the example:",1015 "best_answers_score":0.8,1016 "library_name":"matplotlib",1017 "question_url":"https:\/\/stackoverflow.com\/questions\/7404116\/defining-the-midpoint-of-a-colormap-in-matplotlib",1018 "best_answers_votes":101,1019 "question_length":332,1020 "response_length":31791021 },1022 {1023 "question":"Show matplotlib plots (and other GUI) in Ubuntu (WSL1 & WSL2) So it seems on ubuntu for windows (windows subsystem for linux) people are suggesting we need to use Agg backend and just save images, not show plots. ``` import matplotlib matplotlib.use('Agg') # no UI backend import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2*np.pi*t) plt.plot(t, s) plt.title('About as simple as it gets, folks') #plt.show() plt.savefig(\"matplotlib.png\") #savefig, don't show ``` How could we get it to where plt.show() would actually show us an image? My current option is to override plot.show() to instead just savefig a plot-148123456.png under \/mnt\/c\/Users\/james\/plots\/ in windows and just have an explorer window open viewing the images. I suppose I could host that folder and use a browser. My goal is to be able to run simple examples like the code above without changing the code to ftp the images somewhere etc. I just want the plot to show up in a window. Has anyone figured out a decent way to do it?",1024 "response":"Ok, so I got it working as follows. I have Ubuntu on windows, with anaconda python 3.6 installed. Download and install VcXsrv or Xming (X11 for Windows) from sourceforge(see edit below) sudo apt-get update sudo apt-get install python3.6-tk (you may have to install a different python*-tk depnding on the python version you're using) pip install matplotlib (for matplotlib. but many other things now work too) export DISPLAY=localhost:0.0 (add to ~\/.bashrc to make permanent. see WSL2 below) Anyways, after all that, this code running in ubuntu on wsl worked as is: ``` import matplotlib.pyplot as plt import numpy as np t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2*np.pi*t) plt.plot(t, s) plt.title('About as simple as it gets, folks') plt.show() ``` result: Maybe this is better done through a Jupyter notebook or something, but it's nice to have basic command-line python matplotlib functionality in Ubuntu for Windows on Subsystem for Linux, and this makes many other gui apps work too. For example you can install xeyes, and it will say to install x11-apps and installing that will install GTK which a lot of GUI apps use. But the point is once you have your DISPLAY set correctly, and your x server on windows, then most things that would work on a native ubuntu will work for the WSL. Edit 2019-09-04 : Today I was having issues with 'unable to get screen resources' after upgrading some libraries. So I installed VcXsrv and used that instead of Xming. Just install from https:\/\/sourceforge.net\/projects\/vcxsrv\/ and run xlaunch.exe, select multiple windows, next next next ok. Then everything worked. Edit for WSL 2 users 2020-06-23 WSL2 (currently insider fast ring) has GPU\/docker support so worth upgrade. However it runs in vm. For WSL 2, follow same steps 1-4 then: the ip is not localhost. it's in resolv.conf so run this instead (and include in ~\/.bashrc): ``` export DISPLAY=`grep -oP \"(? Firewall & network protection -> Allow an app through firewall -> make sure VcXsrv has both public and private checked. (When Launching xlaunch first time, you might get a prompt to allow through firewall. This works too. Also, if VcXsrv is not in list of apps, you can manually add it, eg from 'C:\\program files\\vcxsrv\\vcxsrv.exe') Launch VcXsrv with \"Disable access control\" ticked Note: a few WSL2 users got error like couldn't connect to display \"172.x.x.x:0\". If that's you try to check the IP address stored in DISPLAY with this command: echo $DISPLAY. If the showed IP seems to be wrong (i.e. \"8.8.8.8\" or another not working IP address) you need to change the code in ~\/.bashrc showed in the point 5 to something that will get your instance's ip address. One user said this worked: export DISPLAY=$(ifconfig | grep inet | awk '{print $2}' | head -n 1 | awk '{print $0\":0\"}'). However for some others it did not work. YMMV, but just find your IP and use if for DISPLAY. For most WSL2 users, the command in #5 works. Edit for Windows 11 : if MS convinced you to throw out your old computer and buy one with a TPM and so you got Windows 11, you get GUI for free. I hope they add upgrade path to do that on Windows 10 because Win10 will be like XP and last a long time since MS decided you need recent computer even though Win11 would work fine on old computers.",1025 "best_answers_score":0.8,1026 "library_name":"matplotlib",1027 "question_url":"https:\/\/stackoverflow.com\/questions\/43397162\/show-matplotlib-plots-and-other-gui-in-ubuntu-wsl1-wsl2",1028 "best_answers_votes":178,1029 "question_length":1041,1030 "response_length":32711031 },1032 {1033 "question":"Change grid interval and specify tick labels I am trying to plot counts in gridded plots, but I haven't been able to figure out how to go about it. I want: to have dotted grids at an interval of 5; to have major tick labels only every 20; for the ticks to be outside the plot; and to have \"counts\" inside those grids. I have checked for potential duplicates, such as here and here, but have not been able to figure it out. This is my code: ```py import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter for x, y, count in data.values(): fig = plt.figure() ax = fig.add_subplot(111) ax.annotate(count, xy = (x, y), size = 5) # overwrites and I only get the last data point plt.close() # Without this, I get a \"fail to allocate bitmap\" error. plt.suptitle('Number of counts', fontsize = 12) ax.set_xlabel('x') ax.set_ylabel('y') plt.axes().set_aspect('equal') plt.axis([0, 1000, 0, 1000]) # This gives an interval of 200. majorLocator = MultipleLocator(20) majorFormatter = FormatStrFormatter('%d') minorLocator = MultipleLocator(5) # I want the minor grid to be 5 and the major grid to be 20. plt.grid() ``` This is what I get.",1034 "response":"There are several problems in your code. First the big ones: You are creating a new figure and a new axes in every iteration of your loop \u2192 put fig = plt.figure and ax = fig.add_subplot(1,1,1) outside of the loop. Don't use the Locators. Call the functions ax.set_xticks() and ax.grid() with the correct keywords. With plt.axes() you are creating a new axes again. Use ax.set_aspect('equal'). The minor things: You should not mix the MATLAB-like syntax like plt.axis() with the objective syntax. Use ax.set_xlim(a,b) and ax.set_ylim(a,b) This should be a working minimal example: ``` import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(1, 1, 1) # Major ticks every 20, minor ticks every 5 major_ticks = np.arange(0, 101, 20) minor_ticks = np.arange(0, 101, 5) ax.set_xticks(major_ticks) ax.set_xticks(minor_ticks, minor=True) ax.set_yticks(major_ticks) ax.set_yticks(minor_ticks, minor=True) # And a corresponding grid ax.grid(which='both') # Or if you want different settings for the grids: ax.grid(which='minor', alpha=0.2) ax.grid(which='major', alpha=0.5) plt.show() ``` Output is this:",1035 "best_answers_score":0.8,1036 "library_name":"matplotlib",1037 "question_url":"https:\/\/stackoverflow.com\/questions\/24943991\/change-grid-interval-and-specify-tick-labels",1038 "best_answers_votes":280,1039 "question_length":1167,1040 "response_length":11291041 },1042 {1043 "question":"How to set xticks in subplots If I plot a single imshow plot I can use ```py fig, ax = plt.subplots() ax.imshow(data) plt.xticks( [4, 14, 24], [5, 15, 25] ) ``` to replace my xtick labels. Now, I am plotting 12 imshow plots using ```py f, axarr = plt.subplots(4, 3) axarr[i, j].imshow(data) ``` How can I change xticks just for one of these subplots? I can only access the axes of the subplots with axarr[i, j]. How can I access plt just for one particular subplot?",1044 "response":"There are two ways: Use the axes methods of the subplot object (e.g. ax.set_xticks and ax.set_xticklabels) or Use plt.sca to set the current axes for the pyplot state machine (i.e. the plt interface). As an example (this also illustrates using setp to change the properties of all of the subplots): ``` import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=3, ncols=4) # Set the ticks and ticklabels for all axes plt.setp(axes, xticks=[0.1, 0.5, 0.9], xticklabels=['a', 'b', 'c'], yticks=[1, 2, 3]) # Use the pyplot interface to change just one subplot... plt.sca(axes[1, 1]) plt.xticks(range(3), ['A', 'Big', 'Cat'], color='red') fig.tight_layout() plt.show() ```",1045 "best_answers_score":0.8,1046 "library_name":"matplotlib",1047 "question_url":"https:\/\/stackoverflow.com\/questions\/19626530\/how-to-set-xticks-in-subplots",1048 "best_answers_votes":221,1049 "question_length":465,1050 "response_length":6731051 },1052 {1053 "question":"Getting vertical gridlines to appear in line plot in matplotlib I want to get both horizontal and vertical grid lines on my plot but only the horizontal grid lines are appearing by default. I am using a pandas.DataFrame from an sql query in python to generate a line plot with dates on the x-axis. I'm not sure why they do not appear on the dates and I have tried to search for an answer to this but couldn't find one. All I have used to plot the graph is the simple code below. ``` data.plot() grid('on') ``` data is the DataFrame which contains the dates and the data from the sql query. I have also tried adding the code below but I still get the same output with no vertical grid lines. ``` ax = plt.axes() ax.yaxis.grid() # horizontal lines ax.xaxis.grid() # vertical lines ``` Any suggestions?",1054 "response":"You may need to give boolean arg in your calls, e.g. use ax.yaxis.grid(True) instead of ax.yaxis.grid(). Additionally, since you are using both of them you can combine into ax.grid, which works on both, rather than doing it once for each dimension. ``` ax = plt.gca() ax.grid(True) ``` That should sort you out.",1055 "best_answers_score":0.8,1056 "library_name":"matplotlib",1057 "question_url":"https:\/\/stackoverflow.com\/questions\/16074392\/getting-vertical-gridlines-to-appear-in-line-plot-in-matplotlib",1058 "best_answers_votes":127,1059 "question_length":799,1060 "response_length":3111061 },1062 {1063 "question":"prevent plot from showing in jupyter notebook How can I prevent a specific plot to be shown in Jupyter notebook? I have several plots in a notebook but I want a subset of them to be saved to a file and not shown on the notebook as this slows considerably. A minimal working example for a Jupyter notebook is: ``` %matplotlib inline from numpy.random import randn from matplotlib.pyplot import plot, figure a=randn(3) b=randn(3) for i in range(10): fig=figure() plot(b) fname='s%03d.png'%i fig.savefig(fname) if(i%5==0): figure() plot(a) ``` As you can see I have two types of plots, a and b. I want a's to be plotted and shown and I don't want the b plots to be shown, I just want them them to be saved in a file. Hopefully this will speed things a bit and won't pollute my notebook with figures I don't need to see. Thank you for your time",1064 "response":"Perhaps just clear the axis, for example: ``` fig = plt.figure() plt.plot(range(10)) fig.savefig(\"save_file_name.pdf\") plt.close() ``` This will not plot the output in inline mode. I can't work out if it is really clearing the data though.",1065 "best_answers_score":0.8,1066 "library_name":"matplotlib",1067 "question_url":"https:\/\/stackoverflow.com\/questions\/18717877\/prevent-plot-from-showing-in-jupyter-notebook",1068 "best_answers_votes":162,1069 "question_length":840,1070 "response_length":2391071 },1072 {1073 "question":"Matplotlib Legends not working Ever since upgrading matplotlib I get the following error whenever trying to create a legend: ``` \/usr\/lib\/pymodules\/python2.7\/matplotlib\/legend.py:610: UserWarning: Legend does not support [] Use proxy artist instead. http:\/\/matplotlib.sourceforge.net\/users\/legend_guide.html#using-proxy-artist warnings.warn(\"Legend does not support %s\\nUse proxy artist instead.\\n\\nhttp:\/\/matplotlib.sourceforge.net\/users\/legend_guide.html#using-proxy-artist\\n\" % (str(orig_handle),)) \/usr\/lib\/pymodules\/python2.7\/matplotlib\/legend.py:610: UserWarning: Legend does not support [] Use proxy artist instead. http:\/\/matplotlib.sourceforge.net\/users\/legend_guide.html#using-proxy-artist warnings.warn(\"Legend does not support %s\\nUse proxy artist instead.\\n\\nhttp:\/\/matplotlib.sourceforge.net\/users\/legend_guide.html#using-proxy-artist\\n\" % (str(orig_handle),)) ``` This even occurs with a trivial script like this: ``` import matplotlib.pyplot as plt a = [1,2,3] b = [4,5,6] c = [7,8,9] plot1 = plt.plot(a,b) plot2 = plt.plot(a,c) plt.legend([plot1,plot2],[\"plot 1\", \"plot 2\"]) plt.show() ``` I've found the link that the error points me towards pretty useless in diagnosing the source of the error.",1074 "response":"You should add commas: ``` plot1, = plt.plot(a,b) plot2, = plt.plot(a,c) ``` The reason you need the commas is because plt.plot() returns a tuple of line objects, no matter how many are actually created from the command. Without the comma, \"plot1\" and \"plot2\" are tuples instead of line objects, making the later call to plt.legend() fail. The comma implicitly unpacks the results so that instead of a tuple, \"plot1\" and \"plot2\" automatically become the first objects within the tuple, i.e. the line objects you actually want. http:\/\/matplotlib.sourceforge.net\/users\/legend_guide.html#adjusting-the-order-of-legend-items line, = plot(x,sin(x)) what does comma stand for?",1075 "best_answers_score":0.8,1076 "library_name":"matplotlib",1077 "question_url":"https:\/\/stackoverflow.com\/questions\/11983024\/matplotlib-legends-not-working",1078 "best_answers_votes":207,1079 "question_length":1213,1080 "response_length":6701081 },1082 {1083 "question":"How to generate random colors in matplotlib? What's the trivial example of how to generate random colors for passing to plotting functions? I'm calling scatter inside a loop and want each plot a different color. ``` for X,Y in data: scatter(X, Y, c=??) ``` c: a color. c can be a single color format string, or a sequence of color specifications of length N, or a sequence of N numbers to be mapped to colors using the cmap and norm specified via kwargs (see below). Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. c can be a 2-D array in which the rows are RGB or RGBA, however.",1084 "response":"I'm calling scatter inside a loop and want each plot in a different color. Based on that, and on your answer: It seems to me that you actually want n distinct colors for your datasets; you want to map the integer indices 0, 1, ..., n-1 to distinct RGB colors. Something like: Here is the function to do it: ``` import matplotlib.pyplot as plt def get_cmap(n, name='hsv'): '''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct RGB color; the keyword argument name must be a standard mpl colormap name.''' return plt.cm.get_cmap(name, n) ``` Usage in your pseudo-code snippet in the question: ``` cmap = get_cmap(len(data)) for i, (X, Y) in enumerate(data): scatter(X, Y, c=cmap(i)) ``` I generated the figure in my answer with the following code: ``` import matplotlib.pyplot as plt def get_cmap(n, name='hsv'): '''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct RGB color; the keyword argument name must be a standard mpl colormap name.''' return plt.cm.get_cmap(name, n) def main(): N = 30 fig=plt.figure() ax=fig.add_subplot(111) plt.axis('scaled') ax.set_xlim([ 0, N]) ax.set_ylim([-0.5, 0.5]) cmap = get_cmap(N) for i in range(N): rect = plt.Rectangle((i, -0.5), 1, 1, facecolor=cmap(i)) ax.add_artist(rect) ax.set_yticks([]) plt.show() if __name__=='__main__': main() ``` Tested with both Python 2.7 & matplotlib 1.5, and with Python 3.5 & matplotlib 2.0. It works as expected.",1085 "best_answers_score":0.8,1086 "library_name":"matplotlib",1087 "question_url":"https:\/\/stackoverflow.com\/questions\/14720331\/how-to-generate-random-colors-in-matplotlib",1088 "best_answers_votes":201,1089 "question_length":672,1090 "response_length":14271091 },1092 {1093 "question":"Plotting images side by side using matplotlib I was wondering how I am able to plot images side by side using matplotlib for example something like this: The closest I got is this: This was produced by using this code: ``` f, axarr = plt.subplots(2,2) axarr[0,0] = plt.imshow(image_datas[0]) axarr[0,1] = plt.imshow(image_datas[1]) axarr[1,0] = plt.imshow(image_datas[2]) axarr[1,1] = plt.imshow(image_datas[3]) ``` But I can't seem to get the other images to show. I'm thinking that there must be a better way to do this as I would imagine trying to manage the indexes would be a pain. I have looked through the documentation although I have a feeling I may be look at the wrong one. Would anyone be able to provide me with an example or point me in the right direction? EDIT: See the answer from @duhaime if you want a function to automatically determine the grid size.",1094 "response":"The problem you face is that you try to assign the return of imshow (which is an matplotlib.image.AxesImage to an existing axes object. The correct way of plotting image data to the different axes in axarr would be ``` f, axarr = plt.subplots(2,2) axarr[0,0].imshow(image_datas[0]) axarr[0,1].imshow(image_datas[1]) axarr[1,0].imshow(image_datas[2]) axarr[1,1].imshow(image_datas[3]) ``` The concept is the same for all subplots, and in most cases the axes instance provide the same methods than the pyplot (plt) interface. E.g. if ax is one of your subplot axes, for plotting a normal line plot you'd use ax.plot(..) instead of plt.plot(). This can actually be found exactly in the source from the page you link to.",1095 "best_answers_score":0.8,1096 "library_name":"matplotlib",1097 "question_url":"https:\/\/stackoverflow.com\/questions\/41793931\/plotting-images-side-by-side-using-matplotlib",1098 "best_answers_votes":182,1099 "question_length":871,1100 "response_length":7161101 },1102 {1103 "question":"Changing the color of an axis Is there a way to change the color of an axis (not the ticks) in matplotlib? I have been looking through the docs for Axes, Axis, and Artist, but no luck; the matplotlib gallery also has no hint. Any idea?",1104 "response":"When using figures, you can easily change the spine color with: ``` ax.spines['bottom'].set_color('#dddddd') ax.spines['top'].set_color('#dddddd') ax.spines['right'].set_color('red') ax.spines['left'].set_color('red') ``` Use the following to change only the ticks: which=\"both\" changes both the major and minor tick colors ```py ax.tick_params(axis='x', colors='red') ax.tick_params(axis='y', colors='red') ``` And the following to change only the label: ``` ax.yaxis.label.set_color('red') ax.xaxis.label.set_color('red') ``` And finally the title: ``` ax.title.set_color('red') ```",1105 "best_answers_score":0.8,1106 "library_name":"matplotlib",1107 "question_url":"https:\/\/stackoverflow.com\/questions\/1982770\/changing-the-color-of-an-axis",1108 "best_answers_votes":237,1109 "question_length":235,1110 "response_length":5841111 },1112 {1113 "question":"Histogram Matplotlib So I have a little problem. I have a data set in scipy that is already in the histogram format, so I have the center of the bins and the number of events per bin. How can I now plot is as a histogram. I tried just doing ``` bins, n=hist() ``` but it didn't like that. Any recommendations?",1114 "response":"``` import matplotlib.pyplot as plt import numpy as np mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) hist, bins = np.histogram(x, bins=50) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) \/ 2 plt.bar(center, hist, align='center', width=width) plt.show() ``` The object-oriented interface is also straightforward: ``` fig, ax = plt.subplots() ax.bar(center, hist, align='center', width=width) fig.savefig(\"1.png\") ``` If you are using custom (non-constant) bins, you can pass compute the widths using np.diff, pass the widths to ax.bar and use ax.set_xticks to label the bin edges: ``` import matplotlib.pyplot as plt import numpy as np mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200] hist, bins = np.histogram(x, bins=bins) width = np.diff(bins) center = (bins[:-1] + bins[1:]) \/ 2 fig, ax = plt.subplots(figsize=(8,3)) ax.bar(center, hist, align='center', width=width) ax.set_xticks(bins) fig.savefig(\"\/tmp\/out.png\") plt.show() ```",1115 "best_answers_score":0.8,1116 "library_name":"matplotlib",1117 "question_url":"https:\/\/stackoverflow.com\/questions\/5328556\/histogram-matplotlib",1118 "best_answers_votes":268,1119 "question_length":309,1120 "response_length":10271121 },1122 {1123 "question":"Linear regression with matplotlib \/ numpy I'm trying to generate a linear regression on a scatter plot I have generated, however my data is in list format, and all of the examples I can find of using polyfit require using arange. arange doesn't accept lists though. I have searched high and low about how to convert a list to an array and nothing seems clear. Am I missing something? Following on, how best can I use my list of integers as inputs to the polyfit? Here is the polyfit example I am following: ``` import numpy as np import matplotlib.pyplot as plt x = np.arange(data) y = np.arange(data) m, b = np.polyfit(x, y, 1) plt.plot(x, y, 'yo', x, m*x+b, '--k') plt.show() ```",1124 "response":"arange generates lists (well, numpy arrays); type help(np.arange) for the details. You don't need to call it on existing lists. ```py >>> x = [1,2,3,4] >>> y = [3,5,7,9] >>> >>> m,b = np.polyfit(x, y, 1) >>> m 2.0000000000000009 >>> b 0.99999999999999833 ``` I should add that I tend to use poly1d here rather than write out \"m*x+b\" and the higher-order equivalents, so my version of your code would look something like this: ```py import numpy as np import matplotlib.pyplot as plt x = [1,2,3,4] y = [3,5,7,10] # 10, not 9, so the fit isn't perfect coef = np.polyfit(x,y,1) poly1d_fn = np.poly1d(coef) # poly1d_fn is now a function which takes in x and returns an estimate for y plt.plot(x,y, 'yo', x, poly1d_fn(x), '--k') #'--k'=black dashed line, 'yo' = yellow circle marker plt.xlim(0, 5) plt.ylim(0, 12) ```",1125 "best_answers_score":0.8,1126 "library_name":"matplotlib",1127 "question_url":"https:\/\/stackoverflow.com\/questions\/6148207\/linear-regression-with-matplotlib-numpy",1128 "best_answers_votes":246,1129 "question_length":681,1130 "response_length":8121131 },1132 {1133 "question":"Stop matplotlib repeating labels in legend Here is a very simplified example: ``` xvalues = [2,3,4,6] for x in xvalues: plt.axvline(x,color='b',label='xvalues') plt.legend() ``` The legend will now show 'xvalues' as a blue line 4 times in the legend. Is there a more elegant way of fixing this than the following? ``` for i,x in enumerate(xvalues): if not i: plt.axvline(x,color='b',label='xvalues') else: plt.axvline(x,color='b') ```",1134 "response":"plt.legend takes as parameters A list of axis handles which are Artist objects A list of labels which are strings These parameters are both optional defaulting to plt.gca().get_legend_handles_labels(). You can remove duplicate labels by putting them in a dictionary before calling legend. This is because dicts can't have duplicate keys. For example: For Python versions 3.7 As of Python 3.7, dictionaries retain input order by default. Thus, there is no need for OrderedDict form the collections module. ``` import matplotlib.pyplot as plt handles, labels = plt.gca().get_legend_handles_labels() by_label = dict(zip(labels, handles)) plt.legend(by_label.values(), by_label.keys()) ``` Docs for plt.legend",1135 "best_answers_score":0.8,1136 "library_name":"matplotlib",1137 "question_url":"https:\/\/stackoverflow.com\/questions\/13588920\/stop-matplotlib-repeating-labels-in-legend",1138 "best_answers_votes":219,1139 "question_length":434,1140 "response_length":7061141 },1142 {1143 "question":"How to get a matplotlib Axes instance I need to make a candlestick chart using some stock data. For this I want to use the function matplotlib.finance.candlestick(). I need to supply quotes to this function and \"an Axes instance to plot to\". I created some sample quotes as follows: ```py quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)] ``` I now also need an Axes instance though, at which I am a bit lost. I created plots before using matplotlib.pyplot. I now need to do something with matplotlib.axes though, but I am unsure what exactly. Could anybody help me?",1144 "response":"Use the gca (\"get current axes\") helper function: ``` ax = plt.gca() ``` Example: ``` import matplotlib.pyplot as plt import matplotlib.finance quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)] ax = plt.gca() h = matplotlib.finance.candlestick(ax, quotes) plt.show() ```",1145 "best_answers_score":0.8,1146 "library_name":"matplotlib",1147 "question_url":"https:\/\/stackoverflow.com\/questions\/15067668\/how-to-get-a-matplotlib-axes-instance",1148 "best_answers_votes":245,1149 "question_length":614,1150 "response_length":3181151 },1152 {1153 "question":"How can I set the matplotlib 'backend'? I am new user of matplotlib, my platform is Ubuntu 10.04 Python 2.6.5 This is my code ``` import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot([1,2,3]) ``` The error is: ``` \/usr\/local\/lib\/python2.6\/dist-packages\/matplotlib\/backends\/__init__.py:41: UserWarning: Your currently selected backend, 'agg' does not support show(). Please select a GUI backend in your matplotlibrc file ('\/usr\/local\/lib\/python2.6\/dist-packages\/matplotlib\/mpl-data\/matplotlibrc') or with matplotlib.use() (backend, matplotlib.matplotlib_fname())) ``` I installed the Anti-Grain Geometry library apt-get install libagg but it is doesn't work. I tried to use other argument of backend like 'GTK' and 'TkAgg'. I installed python-gtk2-dev package, but still the error is below. Can anyone tell me an executable backend argument and its dependency library? Here is the error: ``` >>> matplotlib.use('GTK') >>> import matplotlib.pyplot as plt Traceback (most recent call last): File \"\", line 1, in File \"\/usr\/local\/lib\/python2.6\/dist-packages\/matplotlib\/pyplot.py\", line 95, in new_figure_manager, draw_if_interactive, show = pylab_setup() File \"\/usr\/local\/lib\/python2.6\/dist-packages\/matplotlib\/backends\/__init__.py\", line 25, in pylab_setup globals(),locals(),[backend_name]) File \"\/usr\/local\/lib\/python2.6\/dist-packages\/matplotlib\/backends\/backend_gtk.py\", line 28, in from matplotlib.backends.backend_gdk import RendererGDK, FigureCanvasGDK File \"\/usr\/local\/lib\/python2.6\/dist-packages\/matplotlib\/backends\/backend_gdk.py\", line 29, in from matplotlib.backends._backend_gdk import pixbuf_get_pixels_array ImportError: No module named _backend_gdk ```",1154 "response":"Your currently selected backend, 'agg' does not support show(). AGG backend is for writing to file, not for rendering in a window. See the backend FAQ at the matplotlib web site. ImportError: No module named _backend_gdk For the second error, maybe your matplotlib distribution is not compiled with GTK support, or you miss the PyGTK package. Try to install it. Do you call the show() method inside a terminal or application that has access to a graphical environment? Try other GUI backends, in this order: TkAgg wxAgg Qt5Agg Qt4Agg",1155 "best_answers_score":0.8,1156 "library_name":"matplotlib",1157 "question_url":"https:\/\/stackoverflow.com\/questions\/4930524\/how-can-i-set-the-matplotlib-backend",1158 "best_answers_votes":121,1159 "question_length":1695,1160 "response_length":5331161 },1162 {1163 "question":"savefig without frames, axes, only content In numpy\/scipy I have an image stored in an array. I can display it, I want to save it using savefig without any borders, axes, labels, titles,... Just pure image, nothing else. I want to avoid packages like PyPNG or scipy.misc.imsave, they are sometimes problematic (they do not always install well), only basic savefig() for me",1164 "response":"EDIT Changed aspect='normal to aspect='auto' since that changed in more recent versions of matplotlib (thanks to @Luke19). Assuming : ```py import matplotlib.pyplot as plt ``` To make a figure without the frame : ```py fig = plt.figure(frameon=False) fig.set_size_inches(w,h) ``` To make the content fill the whole figure ```py ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ``` Then draw your image on it : ```py ax.imshow(your_image, aspect='auto') fig.savefig(fname, dpi) ``` The aspect parameter changes the pixel size to make sure they fill the figure size specified in fig.set_size_inches(\u2026). To get a feel of how to play with this sort of things, read through matplotlib's documentation, particularly on the subject of Axes, Axis and Artist.",1165 "best_answers_score":0.8,1166 "library_name":"matplotlib",1167 "question_url":"https:\/\/stackoverflow.com\/questions\/8218608\/savefig-without-frames-axes-only-content",1168 "best_answers_votes":152,1169 "question_length":372,1170 "response_length":7731171 },1172 {1173 "question":"Pandas plot() without a legend Using the pandas library in python and using ```py .plot() ``` on a dataframe, how do I display the plot without a legend?",1174 "response":"There is a parameter in the function corresponding to legend; by default it is True ``` df.plot(legend=False) ``` Following is the definition of the .plot() method Definition: df.plot(frame=None, x=None, y=None, subplots=False, sharex=True, sharey=False, use_index=True, figsize=None, grid=None, legend=True, rot=None, ax=None, style=None, title=None, xlim=None, ylim=None, logx=False, logy=False, xticks=None, yticks=None, kind='line', sort_columns=False, fontsize=None, secondary_y=False, **kwds)",1175 "best_answers_score":0.8,1176 "library_name":"matplotlib",1177 "question_url":"https:\/\/stackoverflow.com\/questions\/20865487\/pandas-plot-without-a-legend",1178 "best_answers_votes":212,1179 "question_length":153,1180 "response_length":4981181 },1182 {1183 "question":"What is the currently correct way to dynamically update plots in Jupyter\/iPython? In the answers to how to dynamically update a plot in a loop in ipython notebook (within one cell), an example is given of how to dynamically update a plot inside a Jupyter notebook within a Python loop. However, this works by destroying and re-creating the plot on every iteration, and a comment in one of the threads notes that this situation can be improved by using the new-ish %matplotlib nbagg magic, which provides an interactive figure embedded in the notebook, rather than a static image. However, this wonderful new nbagg feature seems to be completely undocumented as far as I can tell, and I'm unable to find an example of how to use it to dynamically update a plot. Thus my question is, how does one efficiently update an existing plot in a Jupyter\/Python notebook, using the nbagg backend? Since dynamically updating plots in matplotlib is a tricky issue in general, a simple working example would be an enormous help. A pointer to any documentation on the topic would also be extremely helpful. To be clear what I'm asking for: what I want to do is to run some simulation code for a few iterations, then draw a plot of its current state, then run it for a few more iterations, then update the plot to reflect the current state, and so on. So the idea is to draw a plot and then, without any interaction from the user, update the data in the plot without destroying and re-creating the whole thing. Here is some slightly modified code from the answer to the linked question above, which achieves this by re-drawing the whole figure every time. I want to achieve the same result, but more efficiently using nbagg. ``` %matplotlib inline import time import pylab as pl from IPython import display for i in range(10): pl.clf() pl.plot(pl.randn(100)) display.display(pl.gcf()) display.clear_output(wait=True) time.sleep(1.0) ```",1184 "response":"Here is an example that updates a plot in a loop. It updates the data in the figure and does not redraw the whole figure every time. It does block execution, though if you're interested in running a finite set of simulations and saving the results somewhere, it may not be a problem for you. The %matplotlib widget magic requires the ipympl Matplotlib Jupyter Extension package. You can install a working environment with pip install jupyter ipympl ``` %matplotlib widget import numpy as np import matplotlib.pyplot as plt import time def pltsin(ax, colors=['b']): x = np.linspace(0,1,100) if ax.lines: for line in ax.lines: line.set_xdata(x) y = np.random.random(size=(100,1)) line.set_ydata(y) else: for color in colors: y = np.random.random(size=(100,1)) ax.plot(x, y, color) fig.canvas.draw() fig,ax = plt.subplots(1,1) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_xlim(0,1) ax.set_ylim(0,1) plt.show() # run this cell to dynamically update plot for f in range(5): pltsin(ax, ['b', 'r']) time.sleep(1) ``` I put this up on nbviewer here, and here's a direct link to the gist",1185 "best_answers_score":0.8,1186 "library_name":"matplotlib",1187 "question_url":"https:\/\/stackoverflow.com\/questions\/34486642\/what-is-the-currently-correct-way-to-dynamically-update-plots-in-jupyter-ipython",1188 "best_answers_votes":77,1189 "question_length":1920,1190 "response_length":10781191 },1192 {1193 "question":"How to set the 'equal' aspect ratio for all axes (x, y, z) When I set up an equal aspect ratio for a 3d graph, the z-axis does not change to 'equal'. So this: ```py fig = pylab.figure() mesFig = fig.gca(projection='3d', adjustable='box') mesFig.axis('equal') mesFig.plot(xC, yC, zC, 'r.') mesFig.plot(xO, yO, zO, 'b.') pyplot.show() ``` Gives me the following: Where obviously the unit length of z-axis is not equal to x- and y- units. How can I make the unit length of all three axes equal? All the solutions I found did not work.",1194 "response":"I like some of the previously posted solutions, but they do have the drawback that you need to keep track of the ranges and means over all your data. This could be cumbersome if you have multiple data sets that will be plotted together. To fix this, I made use of the ax.get_[xyz]lim3d() methods and put the whole thing into a standalone function that can be called just once before you call plt.show(). Here is the new version: ``` from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt import numpy as np def set_axes_equal(ax): \"\"\" Make axes of 3D plot have equal scale so that spheres appear as spheres, cubes as cubes, etc. Input ax: a matplotlib axis, e.g., as output from plt.gca(). \"\"\" x_limits = ax.get_xlim3d() y_limits = ax.get_ylim3d() z_limits = ax.get_zlim3d() x_range = abs(x_limits[1] - x_limits[0]) x_middle = np.mean(x_limits) y_range = abs(y_limits[1] - y_limits[0]) y_middle = np.mean(y_limits) z_range = abs(z_limits[1] - z_limits[0]) z_middle = np.mean(z_limits) # The plot bounding box is a sphere in the sense of the infinity # norm, hence I call half the max range the plot radius. plot_radius = 0.5*max([x_range, y_range, z_range]) ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius]) ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius]) ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius]) fig = plt.figure() ax = fig.add_subplot(projection=\"3d\") # Use this for matplotlib prior to 3.3.0 only. #ax.set_aspect(\"equal\") # # Use this for matplotlib 3.3.0 and later. # https:\/\/github.com\/matplotlib\/matplotlib\/pull\/17515 ax.set_box_aspect([1.0, 1.0, 1.0]) X = np.random.rand(100)*10+5 Y = np.random.rand(100)*5+2.5 Z = np.random.rand(100)*50+25 scat = ax.scatter(X, Y, Z) set_axes_equal(ax) plt.show() ```",1195 "best_answers_score":0.8,1196 "library_name":"matplotlib",1197 "question_url":"https:\/\/stackoverflow.com\/questions\/13685386\/how-to-set-the-equal-aspect-ratio-for-all-axes-x-y-z",1198 "best_answers_votes":92,1199 "question_length":531,1200 "response_length":1804