I tried:
import matplotlib.pyplot as plt
from latex import bm
plt.text(1, 1, "$\bm{q}$")
the error:
ImportError: cannot import name 'bm'
When I use it without from latex import bm it gives nothing and the colors in file are strange (b is black)
There are two issues here, one of which is simpler to fix than the other: the first issue is that the "\b" in your string literal will be interpreted as a Python-level string escape: "\b" is an ASCII backspace character, in the same way that "\t" is a tab character. You need to either escape the backslash so that it gets passed through to LaTeX, or use a raw string. So you need to replace "$\bm{q}$" with either r"$\bm{q}$" or "$\\bm{q}$".
The second issue is that by default, matplotlib's math rendering uses the mathtext library, which doesn't include support for the "\bm" control sequence. If you want to use LaTeX packages not included in mathtext, you can instruct matplotlib to use your local LaTeX installation to render mathematics, instead of using mathtext. You do that with, for example:
from matplotlib import pyplot as plt
plt.rcParams['text.usetex'] = True
Then you need to make sure that the bm package is being used. To do that, you need to change the LaTeX preamble that matplotlib uses:
plt.rcParams['text.latex.preamble'] = [r'\usepackage{bm}']
This does of course mean that you need to have a working LaTeX installation on your machine, and key executables (like latex, dvipng and kpsewhich) need to be on your PATH so that matplotlib can find them.
Once you've done all that, the rendering should work.
Here's a complete self-contained example:
from matplotlib import pyplot as plt
plt.rcParams['text.usetex'] = True
plt.rcParams['text.latex.preamble'] = [r'\usepackage{bm}']
plt.plot([0, 1, 2])
plt.text(1.5, 1, r"$\bm{testing}$")
plt.show()
And here's the image I see when I run the above code on my system (which is equipped with the standard TeX Live installation):
Related
Since a update I have an issue with my ploting in Matplotlib. I use Spyder (as IDE) from Anaconda and do a lot of overlay stuff by running different programm in other to compare simulation.
But recently this does not work anymore ! For example if I run this code (with and without plt.draw does not change anything, and plt.gca as well) :
import numpy as np
import matplotlib.pyplot as plt
f = np.linspace(1,50,20)
x = f**1
y = f**1.2
fig = plt.figure(0)
ax = fig.add_subplot(1,1,1)
ax.plot(f,x)
ax.plot(f,y)
plt.draw()
And re-run it by change a variable as :
y = f**1.5
The output is not what I used to have and expected
I would expected a update of the axis and a third curves (a green one by default) that appears, but no.
Do you have any idea, I turn crazy to find out with this change et how...
Sorry if it's easy, sometimes the easiest thing to do it's the hardest to see.
Thanks and have nice day
I use MikTeX and try to obtain LaTeX fonts in my matplotlib plots.
However, using the demo code, Jyputer Notebook says that there is no latex,
Failed to process string with tex because latex could not be found
I try to add into PATH the path to latex.exe, dvipng.exe and ghostscript. Unfortunately, it still does not work. What I do wrong?
If I evaluate the following
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.sin(np.arange(0, 10, 0.1)),label=r"$\mathcal{M}=2$")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
it returns me the next picture,
So, I see that \mathcal{} command works perfectly, whereas the fonts are not "latex".
You need to add plt.rc('text', usetex=True).
I am writing this script in Spyder (Python 3.5) and I want it to do this:
1) Plot something
2) Allow me to pick some values from the plot
3) Store those values into a variable
4) Do something with that variable
I have checked this thread: Store mouse click event coordinates with matplotlib and modified the function presented there for my own code. The problem I have is that spyder seems to ignore the interactive plot and runs the whole script at once, without waiting for me to pick any values from the plot. As I am using the values for further calculations, I obviously get an error from this. I have even tried to set an input('Press enter to continue...') after the plot, to see if it made it stop and wait for my pickings, but it does not work either.
When I run the script step by step, it works fine, I get the plot, pick my values, print the variable and find all of them in there and use them afterwards. So the question is: how can I make it work when I run the whole script?
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot as plot
def onpick(event):
ymouse = event.ydata
print ('y of mouse: {:.2f}'.format(ymouse))
times.append(ymouse)
if len(times)==5:
f.canvas.mpl_disconnect(cid)
return times
#
t=np.arange(1000)
y=t**3
f=plt.figure(1)
ax=plt.gca()
ax.plot(t,y,picker=5)
times=[]
cid=f.canvas.mpl_connect('button_press_event',onpick)
plt.show()
#Now do something with times
mtimes=np.mean(times)
print(mtimes)
(Spyder maintainer here) I think to solve this problem you need to go to
Preferences > IPython console > Graphics
and turn off the option called Activate support. That will make your script to block the console when a plot is run, so you can capture the mouse clicks you need on it.
The only problem is you need to run
In [1]: %matplotlib qt5
before starting to run your code because Spyder doesn't that for you anymore.
I want to have blank background in my figure, however, it seems that the for some reason the default is not. Here is an example:
import matplotlib.pyplot as plt
x=[1,2]
y=[3,4]
plt.plot(x,y)
This gives me the following figure:
Why do I get this gridded grey background by default? How would one change the default? And perhaps also how would that differ from setting it only for one figure without changing defaults? Thanks
Edit: Apparently, this happened because I imported the seaborn module, as the answer suggested. But why does this behavior occur? So if I want to use both seaborn and matplotlib in one script, I need to keep setting the default background?
What you show in the question isn't actually the matplotlib default style. You may get this because you may have imported some other modules.
To get back the default style use
plt.rcParams.update(plt.rcParamsDefault)
When e.g. seaborn is imported it sets its own style. This is a very greedy behaviour, but you can of course set another style afterwards
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('seaborn-paper')
You may want to look at the style reference.
This question may be of interest when no other style is desired. The idea is, to only load the API, without the styles from seaborn
import seaborn.apionly as sns
I am not sure if this is an acceptable question in SE.
I am wondering if it is possible to edit matplotlib plot interactively. i.e.,
# plot
plt.plot(x, y[1])
plt.plot(x, -1.0*y[2])
plt.show()
will open up a tk screen with the plot. Now, say, I want to modify the linewidth or enter x/y label. Is it possible to do that interactively (either on the screen, using mouse like xmgrace or from a gnuplot like command prompt)?
You can do simple interactive editing with pylustrator
pip install pylustrator
One way to do what (I think) you ask for is to use ipython. ipython is an interactive python environment which comes with many python distributions.
A quick example:
In a cmd, type >>> ipython, which will load the ipython terminal. In ipython, type:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5], 'r-')
fig.show()
Now you have a figure, at the same time as the ipython terminal is "free". This means that you can do commands to the figure, like ax.set_xlabel('XLABEL'), or ax.set_yticks([0, 5]). To make it show on screen, you need to redraw the canvas, which is done by calling fig.canvas.draw().
Note that with ipython, you have full tab-completion with all functions to all objects! Typing fig.get_ and then tab gives you the full list of functions beginning with fig.get_, this is extremely helpful!
Also note that you can run python-scripts in ipython, with run SCRIPT.py in the ipython-cmd, and at the same time having access to all variables defined in the script. They can then be used as above.
Hope this helps!
No, it is not generally possible to do what you want (dynamically interact with a matplotlib using the mouse).
What you see is a rendering of your plot on a "canvas", but it does not include a graphical user interface (GUI) like you have with e.g. xmgrace, Origin etc.
That being said, if you wish to pursue it you have a number of possible options, including:
Modify the matplotlib source code yourself to include a GUI
Do something with buttons, like in YuppieNetworking's answer here:
Change dynamically the contents of a matplotlib plot
But it is probably quicker and more convenient to just use some other plotting software, where someone has already designed a decent user interface for you.
Alternatively, using an iPython notebook to quickly modify your plot script works well enough.
There is a navigation toolbar in qt4agg matplotlib backend which you can add easily. Not much, but at least good scaling...
Not a working code, just some fragments:
from matplotlib.backends.backend_qt4agg import FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
self.figure = Figure(figsize=(5, 3))
self.canvas = FigureCanvas(self.figure)
self.addToolBar(QtCore.Qt.BottomToolBarArea,
NavigationToolbar(self.canvas, self))
Self is your window object derived from QtGui.QMainWindow.