Centering Axes using tight_layout() - python

All,
I'm trying to export figures in (roughly) a particular size so I can include them in high-res in my LaTeX document. When I draw the figure, the ylabel is cutoff (I assume because my figure is small, 2.7in wide). When I call tight_layout(), I get the labels fine, but now the axes are no longer center in the saved image. I need the axes centered above the caption, so I want the axes centered on the image.
I tried adding a second axis to the right side, but I couldn't figure out how to make the labels and ticks invisible for that axis.
Here is without tight_layout()
Here is with tight_layout()
Any idea how I can get the best of both worlds (everything visible, with the axes centered)?
Thanks!

I also encountered this problem and it seems there is no elegent way after I googled it. I ended up with the fig.subplots_adjust.
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([10,20,30])
plt.xlabel('xlabel')
plt.ylabel('ylabel')
fig.patch.set_facecolor('silver')
fig.set_size_inches(w=3.5, h =3)
# %%
#fig.tight_layout()
plt.subplots_adjust(left=0.15, right=0.85, bottom=0.15, top=0.9)
fig.savefig('test.png')
But this will produce additional padding around the axes and tedious parameter-tuning...
while fig.tight_layout() produces:

It would be nice to test it on the code. But try playing with axes.set_position() as shown here: https://www.google.com/amp/s/www.geeksforgeeks.org/matplotlib-axes-axes-set_position-in-python/amp/

Related

python plt barh does cannot properly display the bars

I have problems when drawing horizontal bar chart
firstly if we draw it in plt.bar
plt.figure(figsize=(8,5))
plt.bar(range_df.range_start, range_df.cum_trade_vol, width=30)
plt.show()
but if we draw it in plt.barh
plt.figure(figsize=(8, 5))
plt.barh(range_df.range_start, range_df.cum_trade_vol)
plt.show()
its either
or like:
The problem, I think, is because the crowded data that left too few gaps.
What can we do to properly draw the graph? (since we cannot set width with barh? or can we?)
Maybe another plot package?
Please do not reset the y axis value as the current value is important
The data can be downloaded at
https://drive.google.com/file/d/1y8fHazEFhVR_u2KL6uUsBqv0qmXOd2xT/view?usp=share_link
the notebook is at:
https://colab.research.google.com/drive/1MbjJE4B-mspDRqCYXnDf8hyFRK_uLmRp?usp=sharing
Thank you
I am somewhat unsure of what you are talking about. When writing the horizontal plot, you drop width parameter. There is an equivalent version for plt.barh which is height. So try
plt.barh(range_df.range_start, range_df.cum_trade_vol, height=30)

Why does the title overlap with the plot when specifying x using constrained_layout?

Solved: This problem occurred with matplotlib 3.4, updating to 3.5 fixed the issue.
I am plotting multiple subplots in a graph, which all have titles, labels and subplot titles. To keep everything visible and the right size, I am using constrained_layout.
I would like to add a title that is aligned to the left. However, when I specify the x position (even as 0.5 which is the default), the title overlaps with the graph.
My plots are much more complex, but this already shows my issue:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10, 5), constrained_layout=True)
gs = fig.add_gridspec(1,1)
ax1 = fig.add_subplot(gs[0,0])
fig.suptitle('Title', ha='left')
Only changing the last line of code:
fig.suptitle('Title with x-position', x=0.5, ha='left')
I was first using tight layout, but switched to constrained_layout because tight_layout did not keep the specified size of the figure when exporting it.
I have also switched from subplots to gridspec because I read that constrained_layout does not support subplots.
I know I can add extra space with fig.set_constrained_layout_pads(h_pad=0.3), but this also adds space below the plots, which I would like to avoid.
Hopefully someone can tell me why this happens and how I can get a title aligned to the left that does not overlap with the plot!
The problem occurred in Matplotlib 3.4, updating to 3.5 fixed the issue

How to get colormap plots to fill area?

I'm relatively new to visualization with python. I'm trying to visually show correlation between attributes using a color map, but for some reason the plots aren't filling the entire graph (see pic).
Also, I understand the ticks are bunched (there's 34 attributes), but I wanted to fix the fill issue first. For reference here is the code I have:
correlation = wounds.corr()
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(correlation,cmap='coolwarm', vmin=-1, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0,len(wounds.columns),1)
ax.set_xticks(ticks)
plt.xticks(rotation=90)
ax.set_yticks(ticks)
ax.set_xticklabels(wounds.columns)
ax.set_yticklabels(wounds.columns)
plt.savefig('correlation.jpg')
plt.show()
This is my first time posting here so forgive me if anything is wrong with my question.
Edit: Added code for reference
Best way is to use pandas profiling
Try it out! it would change your life :)
(you can use it directly in your Jupyter notebook):
import pandas_profiling
report = df.profile_report(style={'full_width':True})
If you data is really big you can sample it randomly:
report = df.sample(100000).profile_report(style={'full_width':True})
And you can save it to a file:
report.to_file(output_file="profiling_report.html")

Remove xtick and ytick but keep grid

I'm trying to remove the xtick and ytick so that the final diagram looks like below. I want to keep the guide lines so that it would be easier for referencing. However, in Matplotlib, once you remove the xtick or ytick using the ax.set_xticks([]) or ax.set_yticks([]) method, the grid also disappears. Is there a way to make the plt.grid() function not infer from the xticks or yticks? Any suggestion is much appreciated! Thanks!
Try setting the visibilty:
xticklines = ax.get_xticklines()
for i in xticklines:
i.set_visible(False)

How to set a seaborn swarmplot size and change legend location?

I'm trying to plot a swarmplot with seaborn but I'm struggling with the legend of the plot, I managed to change its position if the figure, but now it is cropped and no information is shown:
I moved the legend with:
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
I changed the size of the figure with no luck
plt.figure(figsize=(12, 10))
I also tried tight_layout() but it just removes the legend from the plot.
Any ideas on how to make it appear on the side of the plot nicely without any cropping on the side or bottom?
Thank you
The legend is not taken into account when plt.tight_layout() tries to optimize the spaces. However you can set the spaces manually using
plt.subplots_adjust()
The relevant argument here is the right side of the figure, so plt.subplots_adjust(right=0.7) would be a good start. 0.7 means that the right part of the axes is at 70% of the total figure size, which should give you enough space for the legend.
Then, you may want to change that number according to your needs.
You can do that like this.
# Import necessary libraries
import seaborn as sns
import matplotlib.pyplot as plt
# Initialize Figure and Axes object
fig, ax = plt.subplots(figsize=(10,4))
# Load in the data
iris = sns.load_dataset("iris")
# Create swarmplot
sns.swarmplot(x="species", y="petal_length", data=iris, ax=ax)
# Show plot
plt.show()
Result is here
Source
(its too late maybe i know but i wanted to share i found already)

Categories

Resources