Remove xtick and ytick but keep grid - python

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)

Related

How to loop over all subplot in a figure to add a new series in it?

Doing the following allow me to create a figure with subplots :
DF.plot(subplots=True, layout=(9,3),figsize = (20,40),sharex=False)
plt.tight_layout()
plt.show()
This works very well. However, I would like to add to all these subplots a new series that would be the same for each subplot.
I think it is possible by browsing all subplot in the figure and then edit each one.
I don't know how to do it and don't know the smartest way to do it, maybe avoid using loop would be faster but I don't know if it is doable.
Assuming that the common serie is DF2['Datas'], how do I add it to all subplots?
DataFrame.plot returns a matplotlib.axes.Axes or numpy.ndarray of them.
axs = DF.plot(subplots=True, layout=(9,3),figsize = (20,40),sharex=False)
for ax in axs.ravel():
DF2['Datas'].plot(ax=ax)

How to get rid of scientifc notation in the y-axis of this .plot.bar() pandas figure?

I tried using plt.ticklabel_format(style='plain'), but since the figure has been created using pandas, df.plot.bar(), it is not working. How can I make this work?
Use the following code:
ax = df.plot.bar(x="Place", y="Amount", rot=30, title="Amount of ...", legend=False)
ax.ticklabel_format(style='plain', axis='y');
Of course, parameters passed to df.plot.bar are according to my source data.
Set them according to your environment.
Importans points are:
save the result of df.plot.bar in a variable (axes object),
set tick label format only for y axis.

Centering Axes using tight_layout()

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/

Why pairplot gives asymmetrical (different upper- and lower-triangle) plots when it should not?

I used a code like:
g = sns.pairplot(df.loc[:,['column1','column2','column3','column4','column5']])
g.map_offdiag(plt.hexbin, gridsize=(20,20))
and have a pairplot and I expect that upper- and lower- triangle plots to be mirrored. The plots look like this:
I thought maybe the problems are the histograms so I tried to tighten the axes using plt.axis('tight') and plt.autoscale(enable=True, axis='y', tight=True) but nothing changed. I also got rid of the diagonal plots (made them invisible), but still the triangle plots are not mirrored. Why? and how to fix it?
Although still I do not understand why pairplot has this behavior here, I found a workaround. I access each plot within pairplot individually and set the limit manually.
g.axes[I,J].set_ylim(df.column3.min(),df.column3.max())
In this case, I had to repeat this piece of code 5 times, where I = 2 and J = 0,1,2,3,4.

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