How to remove all padding in matplotlib subplots when using images [duplicate] - matplotlib

This question already has answers here:
How to combine gridspec with plt.subplots() to eliminate space between rows of subplots
(1 answer)
How to remove the space between subplots in matplotlib.pyplot?
(5 answers)
Closed 3 years ago.
When creating subplots with matplotlib i cannot get tight layout where there would not be any spaces between subplot items.
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(3, 3, figsize=(10,10),gridspec_kw = {'wspace':0, 'hspace':0})
for i, ax in enumerate(axes.ravel()):
im = ax.imshow(np.random.normal(size=200).reshape([10,20]))
ax.axis('off')
plt.tight_layout()
Subplots would consist of images. Seems like there is way to do this when you are not using images. So i assume, there is some configuration about imshow().
I would like to keep aspect ratio of images, but make subplots compact as possible.
this is what i get now, but as you can see, there is a lot of row padding
https://imgur.com/a/u4IntRV

Related

How do I add custom calculated error bars to seaborn bar plots? [duplicate]

This question already has answers here:
How to plot errorbars on seaborn barplot
(1 answer)
Seaborn: Making barplot by group with asymmetrical custom error bars
(1 answer)
How to add error bars on a grouped barplot from a column
(4 answers)
Closed last month.
The situation: university gave us an Excel document. We have a table, just write in our data and we get some tables and plots out. I think the plots are ugly and since I need it for a public presentation, I wanted to redo the plot with seaborn. I managed to actually plot the bars. The only trouble now: I can't add the variance to the bars.
This is my table:
Label,Mean,Error
"Appearance",2.50,0.45
"Functionality",1.90,0.32
"Predictability",2.740,0.52
"Inefficiency",1.701,2.41
This is my code:
import seaborn as sb
import matplotlib.pyplot as plt
import pandas as pd
if __name__ == '__main__':
csv = pd.read_csv('res.csv')
sb.set_theme(style = "darkgrid")
sb.barplot(x = "Mean", y = "Label", data = csv, errorbar="sd")
# plt.savefig('myfile.png', bbox_inches="tight")
plt.show()

How, for one plot only, to change the width with Seaborn/Matplotlib [duplicate]

This question already has answers here:
Matplotlib: get and set axes position
(1 answer)
Matplotlib different size subplots
(6 answers)
How to fully customize subplot size in matplotlib
(2 answers)
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
This code creates following PNG file though, This wasn't what I want.
import seaborn as sns
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,figsize=(20, 6),gridspec_kw={'height_ratios': [2,1]})
fmri = sns.load_dataset("fmri")
flights = sns.load_dataset("flights")
sns.lineplot(data=fmri, x="timepoint", y="signal", hue="event", ax=ax[0])
ax[0].legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.)
sns.lineplot(data=flights, x="year", y="passengers", ax=ax[1])
fig.savefig("test.png")
How can I make the width of second plot longer like this?
It looks easy, but I'm stuck on it..
Edit
The method I came up with was to use GridSpec like a following code, but it is complicated and not intuitive. There is another method that uses ax[0].get_position(), like Redox san taught me, but it is not good enough. I just want to increase the width of second plot a bit, however, Increasing the width of second plot doesn't work. I am still looking for another way.
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(20, 10))
gs = GridSpec(2, 2, width_ratios=[100,1], height_ratios=[2,1])
ax = []
ax.append(plt.subplot(gs.new_subplotspec((0, 0))))
plt.subplot(gs[0,1]).axis('off')
ax.append(plt.subplot(gs.new_subplotspec((1, 0), colspan=2)))
fmri = sns.load_dataset("fmri")
flights = sns.load_dataset("flights")
sns.lineplot(data=fmri, x="timepoint", y="signal", hue="event", ax=ax[0])
ax[0].legend(bbox_to_anchor=(1.02, 1), loc=2, borderaxespad=0.)
sns.lineplot(data=flights, x="year", y="passengers", ax=ax[1])
fig.savefig("test.png")
you can do this by adjusting the widths of the subplots. After plotting (just before save), add these lines. This will get the width information and you can adjust the ratio to what you want it to be
gPos = ax[0].get_position()
gPos.x1 = 0.83 # I have used 83% to set the first plot to be of 83% of original width
ax[0].set_position(gPos)
The plot

matplotlib annotations shift to the right [duplicate]

This question already has answers here:
How to fix overlapping annotations / text
(5 answers)
scatter plot with aligned annotations at each data point
(1 answer)
Closed 9 months ago.
I'm plotting both a line and some scatter points on the line. I want to label the x-coordinate of the scatter points on the line, and the annotations are being obstructed by the line. Without manually inputting the position of the annotations, is there a way to shift all of the annotation texts to the right by a certain amount?
Below is part of the code to produce the scatter plot and annotation.
import numpy as np
import matplotlib.pyplot as plt
fs = 20
figure, ax1 = plt.subplots()
ax1.set_xlim(1.6, 2.0)
ax1.set_ylim(-2, 5)
annotations = ['$1.66$', '$1.68$', '$1.72$', '$1.74$', '$1.76$']
xpoint = [1.66, 1.68, 1.72, 1.74, 1.76]
ypoint = [3.47072347e-01, 5.05186795e+00, 1.61807901e+01, 5.60855544e+01, 6.07027325e+02]
ax1.scatter(xpoint, np.log10(ypoint), color='k')
for i, label in enumerate(annotations):
ax1.annotate(label, (xpoint[i], np.log10(ypoint[i])), ha='left', va='center', fontsize=fs)
ax1.tick_params(labelsize=fs)
figure.savefig("plot.svg", bbox_inches='tight')

How to remove the whitespaces between points in scatterplot [duplicate]

This question already has answers here:
How to change spot edge colors in seaborn scatter plots
(3 answers)
Closed 1 year ago.
I have used the scatterplot command to make a plot of nurse schedules, however whenever the points are close, there is this annoying whitespace, which I would like to get rid of. An example:
So whenever the points are close there appear this white gap...
To plot the red dots I have used this command:
sns.scatterplot(x='xaxis', y='nurses', data=df_plot, marker=',', color='r', s=400,ci=100)
It looks like your markers are being drawn with white edges. You can remove these using edgecolor='None' as an option to sns.scatterplot.
sns.scatterplot(x='xaxis', y='nurses', data=df_plot,
marker=',', color='r', s=400, ci=100, edgecolor='None')
A small example to demonstrate this point:
import matplotlib.pyplot as plt
import seaborn as sns
fig, (ax1, ax2) = plt.subplots(ncols=2)
tips = sns.load_dataset("tips")
sns.scatterplot(ax=ax1, data=tips, x="total_bill", y="tip")
sns.scatterplot(ax=ax2, data=tips, x="total_bill", y="tip", edgecolor='None')

Change histogram bars color [duplicate]

This question already has answers here:
Matplotlib histogram with multiple legend entries
(2 answers)
Closed 4 years ago.
I want to colour different bars in a histogram based on which bin they belong to. e.g. in the below example, I want the first 3 bars to be blue, the next 2 to be red, and the rest black (the actual bars and colour is determined by other parts of the code).
I can change the colour of all the bars using the color option, but I would like to be able to give a list of colours that are used.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(1000)
plt.hist(data,color = 'r')
One way may be similar to approach in other answer:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
data = np.random.rand(1000)
N, bins, patches = ax.hist(data, edgecolor='white', linewidth=1)
for i in range(0,3):
patches[i].set_facecolor('b')
for i in range(3,5):
patches[i].set_facecolor('r')
for i in range(5, len(patches)):
patches[i].set_facecolor('black')
plt.show()
Result: