How can I save figures in matplotlib correctly? [duplicate] - matplotlib

This question already has answers here:
Matplotlib (pyplot) savefig outputs blank image
(5 answers)
Closed 1 year ago.
I have been trying to save my figures using the following code, but the figure being saved in the directory is just blank. What mistake am I doing?
The code I am using is:
import matplotlib as mpl
mpl.matplotlib_fname()
musti = "/Users/Mustafa/Project RS 2/XRF.csv"
df = pd.read_csv(musti)
df
fig = plt.figure(figsize = (3,5))
plt.plot(Cl1, depth, color= "blue", linewidth=1, label='Cl1')
plt.plot(Cl2, depth, color= "green", linewidth=1, label='mean')
plt.plot(Cl3, depth, color= "red", linewidth=1, label='mean')
plt.plot(Cl4, depth, color= "brown", linewidth=1, label='mean')
plt.plot(Cl5, depth, color= "black", linewidth=1, label='mean')
plt.xlabel('Counts')
plt.ylabel('Depth')
plt.ylim(1000, 0)
plt.xlim(750, 2000)
plt.grid(True)
plt.legend(loc=4)
plt.show()
plt.savefig("C:/Users/Mustafa/Python Project/musti.png", bbox_inches="tight", dpi=300, pad_inches=2, transparent=True)

You should switch the order of the last 2 lines. If you show the plot first, it is 'consumed' and there is nothing to save.
plt.savefig("C:/Users/Mustafa/Python Project/musti.png", bbox_inches="tight", dpi=300, pad_inches=2, transparent=True)
plt.show()

Related

Seaborn/Matplotlib: how to remove the horizontal white lines that are overlaying the bars? [duplicate]

This question already has answers here:
how to remove grid lines on image in python?
(4 answers)
How to hide axes and gridlines in Matplotlib (python) [duplicate]
(2 answers)
How to fill legend background color when plotting with TWO axes?
(2 answers)
Closed 28 days ago.
This is how it looks:
I would like to remove the white lines that are overlaying the black bars. Btw: is it possible to remove the background behind the legend?
def stack():
data1 = [
0.7,
0.8,
0.3,
0.6,
0.5
]
data2 = [
20, 30, 23, 17, 28
]
sns.set_theme()
data = np.multiply(data1, 100)
r = [0, 1, 2, 3, 4]
fig, ax1 = plt.subplots()
ax1.bar(r, data, color="black", width=.5)
plt.ylim(0,100)
plt.ylabel('Percent')
plt.xlabel('Lineage')
ax2 = ax1.twinx()
ax2.bar(r, data2, color="red", width=.1)
plt.ylim(0,150)
plt.ylabel("Number")
lgnd1 = mpatches.Patch(color="black", label='Percent')
lgnd2 = mpatches.Patch(color="red", label='Number')
plt.legend(loc='upper center',
bbox_to_anchor=(0.5, 1.2),
ncol=3, handles=[lgnd1, lgnd2])
plt.savefig('number.svg', bbox_inches="tight", transparent=True)
plt.show()
You can use the following code :
plt.grid(False)
Or if you still want the lines you can use:
plt.grid(zorder=0)
plt.bar(range(len(y)), y, width=0.3, align='center', color='skyblue',
zorder=3)
Regarding the color of your legend: You chose this grey by setting the plot default to be the seaborn standard with sns.set_theme() (see seaborn.set_theme).
But, as described there, you are able to override every rc parameter ("runtime configuration parameter") Setting the legend background color to another color should be possible with using the parameter facecolor=... (see matplotlib.pyplot.legend, scroll down a bit )
In your case you can add this parameter here in your legend definition:
plt.legend(loc='upper center',
facecolor='white', # choose your background color
bbox_to_anchor=(0.5, 1.2),
ncol=3, handles=[lgnd1, lgnd2])

How to set a font family to "erewhon" when using Latex in matplotlib?

I am using the latex format for the axis label and axis tick label for some of my plots. My problem is that the latex font differs from the non-latex font which is 'erewhon'. So I want to try to use 'erewhon' in the latex format.
I tried multiple approaches like the following code:
fig, ax1 = plt.subplots(figsize = (8,5))
rcParams = [{'text.usetex': True,
'svg.fonttype': 'none',
'text.latex.preamble': r'\usepackage{erewhon}',
'font.size': 20,
'font.family': 'erewhon',
'mathtext.fontset': 'custom',
'mathtext.rm': 'erewhon',
'mathtext.it': 'erewhon',
'mathtext.bf': 'erewhon'}]
xlabel='Oxygen mass flow (sccm)'
ylabel1=r'$\mathrm{\rho \; (\mu \Omega \cdot cm)}$'
ax1.semilogy(xfit, ( np.exp(m*xfit+b) ) , 'k-', lw=2)
ax1.set_yscale('log')
ax1.set_xlabel(xlabel, fontsize=20)
ax1.set_ylabel(ylabel1, fontsize=20)
This code provides the xlabel font to be 'erewhon' but the ylabel still uses any font (I even don't know which one), although, I use \mathrm{}. Is there any solution for this problem?
Thanks for your help!
Applying the super helpful comment by Ralf Stubner here, this code
import matplotlib.pyplot as plt
preamble = [r"\usepackage[proportional,scaled=1.064]{erewhon}",
r"\usepackage[erewhon,vvarbb,bigdelims]{newtxmath}",
r"\usepackage[T1]{fontenc}",
r"\renewcommand*\oldstylenums[1]{\textosf{#1}}"]
rcParams = {'text.usetex': True,
'svg.fonttype': 'none',
'text.latex.preamble': preamble,
'font.size': 20,
'font.family': 'erewhon'}
plt.rcParams.update(rcParams)
fig, ax1 = plt.subplots(figsize = (8,5))
xlabel='Oxygen mass flow (sccm)'
ylabel1=r'$\mathrm{\rho \; (\mu \Omega \cdot cm)}$'
#ax1.semilogy(xfit, ( np.exp(m*xfit+b) ) , 'k-', lw=2)
ax1.set_yscale('log')
ax1.set_xlabel(xlabel, fontsize=20)
ax1.set_ylabel(ylabel1, fontsize=20)
plt.tight_layout()
plt.show()
produces

Change Pyplot axes text color to white

I have a colorbar that I created for a heatmap image of surface temperature on Earth. The problem that I'm having is that the pyplot figure saves with a white background and I have the Earth image on a black background. I set the figure image to be transparent and need to change the text and ticks on the axes to be white.
I've tried everything I've seen on here and searched for hours on the matplotlib site but nothing seems to work for something as simple as changing text color.
a = np.array([[319.785, 198.988]])
plt.figure(figsize=(7, 1))
img = plt.imshow(a)
plt.gca().set_visible(False)
cax = plt.axes([0, .3, 1, 0.5])
cb = plt.colorbar(orientation='horizontal', cax=cax)
plt.savefig("colorbar.png", bbox_inches='tight', transparent=True)
plt.show()
You can set the color of the ticks, the color of the labels and the color of the axes edges all to white using the rcParams as follows.
import matplotlib.pyplot as plt
import numpy as np
params = {"ytick.color" : "w",
"xtick.color" : "w",
"axes.labelcolor" : "w",
"axes.edgecolor" : "w"}
plt.rcParams.update(params)
a = np.array([[319.785, 198.988]])
fig =plt.figure(figsize=(7, 1))
# set facecolor black for testing:
fig.set_facecolor("k")
img = plt.imshow(a)
plt.gca().set_visible(False)
cax = plt.axes([0, .3, 1, 0.5])
cb = plt.colorbar(orientation='horizontal', cax=cax)
plt.show()

matplotlib line plot dont show vertical lines in step function

I do have a plot that only consists of horizontal lines at certain values when I have a signal, otherwise none. So, I am looking for a way to plot this without the vertical lines. there may be gaps between the lines when there is no signal and I dont want the lines to connect nor do I want a line falling off to 0. Is there a way to plot this like that in matplotlib?
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
axes = self.figure.add_subplot(111)
axes.plot(df.index, df["x1"], lw=1.0, c=self.getColour('g', i), ls=ls)
The plot you are looking for is Matplotlib's plt.hlines(y, xmin, xmax).
For example:
import matplotlib.pyplot as plt
y = range(1, 11)
xmin = range(10)
xmax = range(1, 11)
colors=['blue', 'green', 'red', 'yellow', 'orange', 'purple',
'cyan', 'magenta', 'pink', 'black']
fig, ax = plt.subplots(1, 1)
ax.hlines(y, xmin, xmax, colors=colors)
plt.show()
Yields a plot like this:
See the Matplotlib documentation for more details.

How to plot multiple colour on ylable using matplotlib?

I have list of data want to plot on a subplot. Then I want to lable ylable with different set of colour. See the simple code example below:-
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('yellow red blue')
plt.show()
This produces the following image:-
In the resultant image ylable is named as 'yellow red blue' and all in black colour. But I would like to have this label coloured like this:-
'yellow' with yellow colour,
'red' with red colour
and 'blue' with blue colour.
Is it possible with matplotlib?
No. You can't do this with a single text object. You could manually add three different labels, i.e.:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
ax = plt.gca()
ax.text(-0.1, 0.4, 'yellow', color='yellow', rotation=90, transform=ax.transAxes)
ax.text(-0.1, 0.5, 'red', color='red', rotation=90, transform=ax.transAxes)
ax.text(-0.1, 0.6, 'blue', color='blue', rotation=90, transform=ax.transAxes)
plt.show()