matplotlib figure image saved without figure title and axis - python

The following code gives the figure like the image below.
plt.subplot(1,1,1)
ax = sns.barplot(x=contr, y=X.columns)
ax.bar_label(ax.containers[0])
plt.title('Contribution')
plt.savefig('result_image.png')
plt.show()
What I can see in the jupyter notebook
However, the saved image ('result_image.png') has no titles or axis, but literally just figure box itself like the picture below
the real image file is like this
What I wanted is the plt image with title and axis.
=====
EDIT
The real problem was not the crop of the figure,
but the figure background being transparent.
(I didn't notice because the background of my photo application was dark)
I solved the problem with the code below.
plt.savefig('result_image.png', facecolor='white')

The real problem was not the crop of the figure, but the figure background being transparent.
(I didn't notice because the background of my photo application was dark)
I solved the problem with the codes below.
plt.savefig('result_image.png', facecolor='white')
or
plt.savefig('result_image.jpg')

Related

Problem plotting a raster (GeoTIFF) on top of a basemap (Google Maps / Mapbox) with Python

I've been stuck for a few days trying to plot a TIF file over a basemap (Google Maps or Mapbox) using Python. I don't know if this is actually possible because I didn't find examples and nothing very clear about it, the most I found is how to plot vector files (shp) on top of basemaps, but nothing about raster.
I have a raster (rainfall_clipped.tif) that is in EPSG:4326 and I'm trying to plot it on top of a MapBox map using the Contextily package. At first I suspected that it could be a projection problem, but even doing the conversions to EPSG:3857, it didn't work. In the documentation Contextily says that it accepts both projections.
Contextily seems to understand the projections, even because it generates the map with the correct axes, the big problem is that it doesn't plot the TIF file on the map. And it's also reading the raster because it loaded the colorbar with the correct values. I don't know if the layer order is wrong or what else it could be.
Below is the code I am using and then the image that is being generated:
data = rasterio.open("rainfall_clipped.tif")
# Read the bounds
left, bottom, right, top = data.bounds
# Create a figure and axes
fig, ax = plt.subplots(figsize=(10, 10))
# Add the raster data to the plot using imshow
im = ax.imshow(data.read(1), extent=[left, right, bottom, top], cmap="Blues")
# Add a colorbar
fig.colorbar(im, ax=ax)
# Add a basemap using contextily
ctx.add_basemap(ax, crs=data.crs, source=ctx.providers.MapBox(accessToken="my_key", id="mapbox/satellite-v9"))
# Show the plot
plt.show()
This code is generating this image:
Output image
What I'm trying to do is something like below:
Expected image
Any suggestions what I can do?

Errorbars matplotliby python

i would like to know how i can add errorbars to my plot. Im attaching pic of code and plotenter image description here

Inline figure saved as PNG from Jupyter notebook shows black margin in IrfanView

This minimal example (as the only cell of am ipython/yupiter notebook)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.savefig('test.png')
yields the expected empty plot in the code cell but a PNG file that IrfanView presents with a black margin instead of the ticks and tick labels. Inspection in IrfanView ruled out a problem of transparency. I have also tried fig.tight_layout() and plt.savefig.
Versions are
Windows 10
IrfanView 4.44 - 64 bit
kernel: 6.2.0
matplotlib: 3.3.4
python: 3.9.0
EDIT: SVG and PDF are fine, even PNG looks fine in Paint, while paint.net reveals a transparent background at the margin. My previous inspection with IrfanView consisted of selecting the white of the inner area as transparent color, which obviously changed the formerly transparent background of the margin to black :-(
EDIT 2: IrfanView can be configured to show transparent pixels in other colors than black (Options > Properties > Viewing > Main Window Color), but that setting is applied to transparent pixels only on reload/reopening.
This is what your code produces as test.png for me:
Perhaps you can post your figure to be clearer what the problem is. What backend are you using? Find out with:
import matplotlib
matplotlib.get_backend()
Maybe using set_facecolor could help?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.patch.set_facecolor('white')
fig.savefig('test.png')

Margins in 2D image plot after adding scatterplot point in Matplotlib

I am trying to label points on the image, but whenever I do an extra marker on the plots by coordinate values and the margins becomes unnecessarily large. What is the issue here, and is there a way to fix this?
The image is fine. I even plotted it below and everything seems okay when I don't add the plotted point.
imp = plt.imshow(processed[::-1],cmap='gray_r',vmin=1000,vmax=2000)
plt.colorbar()
plt.figure()
imp = plt.imshow(processed[::-1],cmap='gray_r',vmin=1000,vmax=2000)
plt.plot(600,400,'*',color='r')
plt.colorbar()
Large Margin around image generated

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?
Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.
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]: [<matplotlib.lines.Line2D at 0x3f29750>]
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.
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
As a reminder, the plt.savefig() should be written before the plt.show(), otherwise, a transparent image will be created (without the actual plot).
For high-quality images:
plt.savefig('filename.png', format='png', dpi='600', transparent=True)
plt.show()

Categories