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

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')

Related

Bold some but not all characters of plot title [duplicate]

This question already has answers here:
Make part of a matplotlib title bold and a different color
(3 answers)
Closed 8 months ago.
Is it possible to have some but not all letters of an axes title in bold? I could not find anything in the documentation, but wondering if there is a workaround.
Example:
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot([1,2,3])
ax2.plot([-1,-2,-3])
ax1.set(title="A. line with positive slope")
ax2.set(title="B. line with negative slope")
# want...
ax1.set(title="bold(A.) line with positive slope")
I would like A. and B. to be bold in the titles.
Try this:
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot([1,2,3])
ax2.plot([-1,-2,-3])
# ax1 = plt.gca()
ax1.set(title=r'$\bf{A}$. line with positive slope')
ax2.set(title=r'$\bf{B}$. line with negative slope')

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

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:

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

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

Adding splitplot (dotplot) to grouped boxplot - Panda and Seaborn

I am using seaborn for first time, and trying to make a nested (grouped) boxplot with data-points added as dots. Here is my code:
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
sns.set(style="ticks")
## Draw a nested boxplot to show bills by day and sex
sns.boxplot(x="day", y="total_bill", hue="smoker",data=tips,width=0.5,palette="PRGn",linewidth=1)
## Draw a split strip plot
sns.stripplot(x="day", y="total_bill", hue="smoker",palette="PRGn",data=tips,size=4,edgecolor="gray",
split=True)
sns.despine(offset=10, trim=True)
plt.show()
And the figure:
You see that dots are not centered to boxes, because of the 'width' parameter used in boxplots. Is there any way I can align dots to boxes? The width parameter in boxplot command is the reason for unaligned dots.
p.s. - I have added the MCVE as mentioned by tom.
Bade
The distance between groups is computed automatically and there's no simple way to change it that I am aware of, but you are using an indirect way to modify it in the boxplot: the keyword width. Use the default value and everything will align.
sns.set(style="ticks")
sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips,
palette="PRGn", linewidth=1)
sns.stripplot(x="day", y="total_bill", hue="smoker", data=tips,
palette="PRGn", size=4, edgecolor="gray", split=True)
sns.despine(offset=10, trim=True)