Seaborn white axes for black background presentation [duplicate] - matplotlib

This question already has answers here:
Best way to display Seaborn/Matplotlib plots with a dark iPython Notebook profile
(4 answers)
Closed last year.
I need help with styling the axes of the graph given below. I need to enforce the axes as well as their labels to be white so as the png fits on a black background.
As a sample code I provide the standard:
# loading dataset
data = sns.load_dataset("iris")
# draw lineplot
sns.lineplot(x="sepal_length", y="sepal_width", data=data)
plt.tight_layout()
plt.show()
fig.savefig('MyImage.png', transparent=True)
which will provide
So, essentially, I would like that the 4 axes and the labels become white.

You can use a dark style:
import matplotlib.pyplot as plt
plt.style.use('dark_background')

Related

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

Save a corner plot in matplotlib figure

I have a simple corner plot. Lets just imagine the example from their page (taken from here):
import corner
import numpy as np
ndim, nsamples = 2, 10000
np.random.seed(42)
samples = np.random.randn(ndim * nsamples).reshape([nsamples, ndim])
figure = corner.corner(samples)
Now I want to ask, can I save this full canvas(of 3 plots together) in a single matplotlib figure, so that I may be able to inset this plot in another bigger matplotlib plot.
Additionally I have another question, is there a way to put custom legend/title on corner plots ?
this is my first post on Stack Overflow, with less than 50 reputation I cannot post this as a comment, hope it is helpful to some extent.
Using this line to save the figure of corner plots:
corner.corner.savefig('cornerplot...')
Perhaps this is adjustable and can be reloaded as matplotlib subplot objects. Though understanding the source code would certainly be best

Geopandas & Mapplotlib, how do I plot without an outline around any shape?

When I run the code below in a Jupyter Notebook,
I get a map of the world, colored in red.
There are fine white-ish lines between the countries.
Is there a way to plot the world so that all countries
are solid and there's no line in between?
I'm asking, because my real world usecase is a fine grid that
behaves just like the world map: Each grid shape has a fine outline
which I do not want to have in the plot. (Update, since this was asked: The grid shapes will not have the same fill color.
)
import geopandas as gpd
import geoplot as gplt
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world['total'] = 1
world.plot(column='total', cmap='Set1')
For the grid example, the grid files are at https://opendata-esri-de.opendata.arcgis.com/datasets/3c1f46241cbb4b669e18b002e4893711_0
A simplified example that shows the problem.
sf = 'Hexagone_125_km/Hexagone_125_km.shp'
shp = gpd.read_file(sf)
shp.crs = {'init': 'epsg:4326'}
shp['sum'] = 1 # for example, fill sum with something
shp.plot(figsize=(20,20), column='sum', cmap='gnuplot', alpha=1, legend=True)
The white lines are due to antialiasing. This usually makes the visual more smooth, but leads to white lines in between different shapes. You can turn off anialiasing via
antialiased=False
That has the inevitable drawback of the plot looking pixelated.
An alternative is to give the patches an edge with a certain linewidth. The edges should probably have the same color as the faces, so
edgecolor="face", linewidth=0.4
would be an option. This removes the white lines, but introduces a slight "searing" effect (You'll notice mainly looking at islands like Indonesia or Japan). This will be the more noticable, the smaller the features, so it may be irrelevant for showing a hexbin plot. Still, playing a bit with the linewidth might improve the result further.
Code for reproduction:
import numpy as np; np.random.seed(42)
import geopandas as gpd
import matplotlib.pyplot as plt
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world['total'] = np.random.randint(0,10, size=len(world))
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(7,10))
world.plot(column='total', cmap='Set1', ax=ax1)
world.plot(column='total', cmap='Set1', ax=ax2, antialiased=False)
world.plot(column='total', cmap='Set1', ax=ax3, edgecolor="face", linewidth=0.4)
ax1.set_title("original")
ax2.set_title("antialiased=False")
ax3.set_title("edgecolor='face', linewidth=0.4")
plt.tight_layout()
plt.savefig("world.png")
plt.show()

Matplotlib: How to plot an empty circle in an scatter plot using pandas plot api? [duplicate]

This question already has answers here:
How to do a scatter plot with empty circles in Python?
(6 answers)
Closed 4 years ago.
I'm trying to plot a scatter plot with pandas api where each point is an empty circle, just with border color and transparency. I've tried a lot of tweaks in this code:
ax = ddf.plot.scatter(
x='espvida',
y='e_anosestudo',
c=ddf['cor'],
alpha=.2,
marker='o');
The generated plot looks like this:
If you look closely at the points:
you'll see that they have a transparent fill color and a border. I'd like it to have just a transparent border. Hou would I do it?
I can't seem to get it to work with DataFrame.plot.scatter; it doesn't seem to respect the facecolors='none' kwarg, likely because some default color argument is being passed to plt.scatter.
Instead, fall back to matplotlib, specifying facecolors='none' and setting the edgecolors to the column in your df that represents the color.
Sample Data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'x': np.random.normal(1,1,1000),
'y': np.random.normal(1,1,1000),
'color': list('rgby')*250})
plt.scatter(df.x.values, df.y.values, facecolors='none', edgecolors=df['color'], alpha=0.2, s=100)
plt.show()
From the matplotlib scatter doc:
edgecolors : color or sequence of color, optional, default: 'face'. The edge color of the marker. Possible values:
'face': The edge color will always be the same as the face color.
'none': No patch boundary will be drawn.
A matplotib color.
For non-filled markers, the edgecolors kwarg is ignored and forced to 'face' internally
Try add: edgecolors='none':
ax = ddf.plot.scatter(
x='espvida',
y='e_anosestudo',
c=ddf['cor'],
alpha=.2,
marker='o',
edgecolors='none);

How do I use colourmaps with variable alpha in a Seaborn kdeplot without seeing the contour lines?

Python version: 3.6.4 (Anaconda on Windows)
Seaborn: 0.8.1
Matplotlib: 2.1.2
I'm trying to create a 2D Kernel Density plot using Seaborn but I want each step in the colourmap to have a different alpha value. I had a look at this question to create a matplotlib colourmap with alpha values: Add alpha to an existing matplotlib colormap.
I have a problem in that the lines between contours are visible. The result I get is here:
I thought that I had found the answer when I found this question: Hide contour linestroke on pyplot.contourf to get only fills. I tried the method outlined in the answer (using set_edgecolor("face") but it did not work in this case. That question also seemed to be related to vector graphics formats and I am just writing out a PNG.
Here is my script:
import numpy as np
import seaborn as sns
import matplotlib.colors as cols
import matplotlib.pyplot as plt
def alpha_cmap(cmap):
my_cmap = cmap(np.arange(cmap.N))
# Set a square root alpha.
x = np.linspace(0, 1, cmap.N)
my_cmap[:,-1] = x ** (0.5)
my_cmap = cols.ListedColormap(my_cmap)
return my_cmap
xs = np.random.uniform(size=100)
ys = np.random.uniform(size=100)
kplot = sns.kdeplot(data=xs, data2=ys,
cmap=alpha_cmap(plt.cm.viridis),
shade=True,
shade_lowest=False,
n_levels=30)
plt.savefig("example_plot.png")
Guided by some comments on this question I have tried some other methods that have been successful when this problem has come up. Based on this question (Matplotlib Contourf Plots Unwanted Outlines when Alpha < 1) I have tried altering the plot call to:
sns.kdeplot(data=xs, data2=ys,
cmap=alpha_cmap(plt.cm.viridis),
shade=True,
shade_lowest=False,
n_levels=30,
antialiased=True)
With antialiased=True the lines between contours are replaced by a narrow white line:
I have also tried an approach similar to this question - Pyplot pcolormesh confused when alpha not 1. This approach is based on looping over the PathCollections in kplot.collections and tuning the parameters of the edges so that they become invisible. I have tried adding this code and tweaking the linewidth -
for thing in kplot.collections:
thing.set_edgecolor("face")
thing.set_linewidth(0.01)
fig.canvas.draw()
This results in a mix of white and dark lines - .
I believe that I will not be able to tune the line width to make the lines disappear because of the variable width of the contour bands.
Using both methods (antialiasing + linewidth) makes this version, which looks cool but isn't quite what I want:
I also found this question - Changing Transparency of/Remove Contour Lines in Matplotlib
This one suggests overplotting a second plot with a different number of contour levels on the same axis, like:
kplot = sns.kdeplot(data=xs, data2=ys,
ax=ax,
cmap=alpha_cmap(plt.cm.viridis),
shade=True,
shade_lowest=False,
n_levels=30,
antialiased=True)
kplot = sns.kdeplot(data=xs, data2=ys,
ax=ax,
cmap=alpha_cmap(plt.cm.viridis),
shade=True,
shade_lowest=False,
n_levels=35,
antialiased=True)
This results in:
This is better, and almost works. The problem here is I need variable (and non-linear) alpha throughout the colourmap. The variable banding and lines seem to be a result of the combinations of alpha when contours are plotted over each other. I also still see some clear/white lines in the result.