Unable to use latex for matplotlib ticks - python

I am trying to set the ticks on the axis of a matplotlib plot using latex. While the latex for the title and the labels for the x and y axis are rendering correctly, the text for the ticks do not render correctly.
The following is an example:
import matplotlib as mpl
import numpy as np
from matplotlib import pyplot as plt
mpl.rcParams["mathtext.fontset"] = "stix"
mpl.rcParams['font.family'] = 'STIXGeneral'
x = np.arange(1,4)
y = x*x
plt.plot(x, y)
plt.xlabel(r"$\mathfrak{X}$")
plt.ylabel(r"$\mathfrak{Y}$")
plt.title(r"$\mathfrak{T}$")
frame = plt.gca()
frame.set_xticklabels(r'$\mathfrak{t}_i$')
plt.show()
Running this code, I get the following result:
As you can see the x ticks are not rendered correctly.
I have also enabled text.usetex on rcParams. But that causes another problem. Here is an example:
import matplotlib as mpl
import numpy as np
from matplotlib import pyplot as plt
mpl.rcParams["mathtext.fontset"] = "stix"
mpl.rcParams['font.family'] = 'STIXGeneral'
plt.rc('text', usetex=1)
mpl.rcParams['text.latex.preamble'].append(r'\usepackage{amsfonts}')
x = np.arange(1,4)
y = x*x
plt.plot(x, y)
plt.xlabel(r"$\mathfrak{X}$")
plt.ylabel(r"$\mathfrak{Y}$")
plt.title(r"$\mathfrak{T}$")
frame = plt.gca()
frame.set_xticklabels(r"$\mathfrak{Q}$")
plt.show()
Running this code, I will get an error saying LaTeX was not able to process the following string: '$'. There will be no problem if I don't use latex for the ticks.
Should I set some other parameters to use latex for the ticks? Also, it is important for me to use "stix" font for the ticks.
I appreciate any help on this issue.

Related

How to save figure in Matplotlib in Python

I am trying to save my figure in Matplotlib to a file but when I run the command to save the image, it doesn't give any errors but I can't see the file.
plt.savefig('Traveling Salesmen Graph.png')
pyplot keeps track of the "current figure", and functions called on the library which require a figure operate on that, but you can also be more explicit by calling savefig() on the figure object.
as an example from https://pythonspot.com/matplotlib-save-figure-to-image-file/:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
#plt.show()
fig.savefig('plot.png')
Being explicit in this way should solve your issue.
For references to pyplot functions which operate on the "current figure" see: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.html

How to plot and display a graph in Python

I wrote the code to plot and display a simple graph in Python:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import interactive
interactive(True)
x = np.arange(0,5,0.1)
y = np.sin(x)
plt.plot(x,y)
plt.show
And all I got is a blank screen.
And when I remove the "interactive" thing it shows no error but diplays nothing.
How can I display the graph?
(P.S: I use Python 2.7)
Remove these lines, they are not for a simple graphic:
from matplotlib import interactive
interactive(True)
And you're missing the () in the plt.show()
plt.show()
There is a syntax error. Replace plt.show with plt.show()
Just a note for others for future reference the full code should also include plt.figure() with the interactive elements removed.
Here what I came up with.
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()
But this may be a 3.5 problem I've not tried in 2.7
You can also plot graphs with pyformulas.
First pip install pyformulas, then
import pyformulas as pf
import numpy as np
x = np.linspace(-10,10,100)
y = x**2 + x*np.e**(np.cos(x)**2)
pf.plot(x, y)
Disclaimer: I'm the maintainer of pyformulas

Can't plot a bar chart

I want to simply draw plot. But I am having an interesting message instead of plot. It is not an error message, I have seen such a message before. The message is the following:
<matplotlib.figure.Figure at 0x1c4150890>
The code is:
import matplotlib.pyplot
x = [1,2,3,4]
y = [1,4,9,16]
fig = plt.figure()
plt.scatter(x,y)
plt.show()
Any help will be appreciated.
Seems like you are trying to print a matplotlib-Figure object as a string (print fig or something). Is the code above really what you're executing?
I had to change it to
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [1,4,9,16]
fig = plt.figure()
plt.scatter(x,y)
plt.show()
to make it work:
Besides, this is a scatter plot and not a bar chart.
It worked with the following code:
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
Good luck!

Filling region between curve and x-axis in Python using Matplotlib

I am trying to simply fill the area under the curve of a plot in Python using MatPlotLib.
Here is my SSCCE:
import json
import pprint
import numpy as np
import matplotlib.pyplot as plt
y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791]
x = np.arange(len(y))
fig2, ax2 = plt.subplots()
ax2.fill(x, y)
plt.savefig('picForWeb.png')
plt.show()
The attached picture shows the output produced.
Does anyone know why Python is not filling the entire area in between the x-axis and the curve?
I've done Google and StackOverflow searches, but could not find a similar example. Intuitively it seems that it should fill the entire area under the curve.
I usually use the fill_between function for these kinds of plots. Try something like this instead:
import numpy as np
import matplotlib.pyplot as plt
y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791]
x = np.arange(len(y))
fig, (ax1) = plt.subplots(1,1);
ax1.fill_between(x, 0, y)
plt.show()
See more examples here.
If you want to use this on a pd.DataFrame use this:
df.abs().interpolate().plot.area(grid=1, linewidth=0.5)
interpolate() is optional.
plt.fill assumes that you have a closed shape to fill - interestingly if you add a final 0 to your data you get a much more sensible looking plot.
import numpy as np
import matplotlib.pyplot as plt
y = [0,0,0,0,0,0,0,0,0,0,0,863,969,978,957,764,767,1009,1895,980,791,0]
x = np.arange(len(y))
fig2, ax2 = plt.subplots()
ax2.fill(x, y)
plt.savefig('picForWeb.png')
plt.show()
Results in:
Hope this helps to explain your odd plot.

PyLab: Plotting axes to log scale, but labelling specific points on the axes

Basically, I'm doing scalability analysis, so I'm working with numbers like 2,4,8,16,32... etc and the only way graphs look rational is using a log scale.
But instead of the usual 10^1, 10^2, etc labelling, I want to have these datapoints (2,4,8...) indicated on the axes
Any ideas?
There's more than one way to do it, depending on how flexible/fancy you want to be.
The simplest way is just to do something like this:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x = np.exp2(np.arange(10))
plt.semilogy(x)
plt.yticks(x, x)
# Turn y-axis minor ticks off
plt.gca().yaxis.set_minor_locator(mpl.ticker.NullLocator())
plt.show()
If you want to do it in a more flexible manner, then perhaps you might use something like this:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x = np.exp2(np.arange(10))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.semilogy(x)
ax.yaxis.get_major_locator().base(2)
ax.yaxis.get_minor_locator().base(2)
# This will place 1 minor tick halfway (in linear space) between major ticks
# (in general, use np.linspace(1, 2.0001, numticks-2))
ax.yaxis.get_minor_locator().subs([1.5])
ax.yaxis.get_major_formatter().base(2)
plt.show()
Or something like this:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x = np.exp2(np.arange(10))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.semilogy(x)
ax.yaxis.get_major_locator().base(2)
ax.yaxis.get_minor_locator().base(2)
ax.yaxis.get_minor_locator().subs([1.5])
# This is the only difference from the last snippet, uses "regular" numbers.
ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
plt.show()

Categories