Make bold the lines around a plot matplotib [duplicate] - python

This question already has answers here:
How to change Border width in MatPlotLib?
(1 answer)
How to add border or frame around individual subplots
(2 answers)
matplotlib border width
(3 answers)
How to add black border to matplotlib 2.0 `ax` object In Python 3?
(3 answers)
Closed 19 days ago.
How can I make a plot surrounded with a bold line, like so?

I would use the set_linewidth and set_color parameters from matplotlib spines :
An axis spine -- the line noting the data area boundaries.
import matplotlib.pyplot as plt
C, W, L, T = "black", 4, 2, 7 # <- adjust here
#Color, Width, Length, Tickness --------------
fig, ax = plt.subplots(figsize=(W, L))
list_of_spines = ["left", "right", "top", "bottom"]
for sp in list_of_spines:
ax.spines[sp].set_linewidth(T)
ax.spines[sp].set_color(C)
ax.set_xticks([])
ax.set_yticks([])
plt.show();
Output :

You could use the following code that was the
answer on a similar question
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.rcParams["axes.edgecolor"] = "black"
plt.rcParams["axes.linewidth"] = 2.50
fig = plt.figure(figsize = (4.1, 2.2))
ax = fig.add_subplot(111)

You can set the width and colour of a border around the image like so:
from matplotlib import pyplot as plt
# some data for demonstration purposes
import numpy as np
x = np.random.randn(100)
# create figure
fig, ax = plt.subplots()
ax.plot(x)
# set the border width
fig.set_linewidth(10)
# set the border colour (to black in this case)
fig.set_edgecolor("k")
# show the figure
fig.show()
This gives:

Related

How to add an image as the background to a matplotlib figure (not to plots, but to the "whitespace" ala set_face() )

I am trying to add an image to the "whitespace" behind the various subplots of a matplotlib figure.
Most discussions similar to this topic are to add images to the plots themselves, however I have not yet come across a means to change the background of the overall "canvas".
The most similar function I have found is set_facecolor(), however this only allows a single color to be set as the background.
fig, ax = plt.subplots(2,2)
fig.patch.set_facecolor('xkcd:mint green')
plt.show()
However, I am seeking a solution to import an image behind the plots, similar to this (manually made):
I have googled, searched SO, and looked through the matplotlib docs but I only get results for either plt.imshow(image) or set_facecolor() or similar.
You can use a dummy subplot, with the same size as the figure, and plot the background onto that subplot.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
image = plt.imread('test.jpg')
# make ticks white, for readability on colored background
mpl.rcParams.update({'xtick.color': "white",
'ytick.color': "white",
'axes.labelcolor': "white"})
# create a figure with 4 subplots, with the same aspect ratio as the image
width = 8
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(width, width * image.shape[0] / image.shape[1]))
for ax in np.ravel(axs):
ax.patch.set_alpha(0.7) # make subplots semi-transparent
background_ax = plt.axes([0, 0, 1, 1]) # create a dummy subplot for the background
background_ax.set_zorder(-1) # set the background subplot behind the others
background_ax.imshow(image, aspect='auto') # show the backgroud image
# plot something onto the subplots
t = np.linspace(0, 8 * np.pi, 2000)
for i in range(2):
for j in range(2):
axs[i, j].plot(np.sin(t * (i + 2)), np.sin(t * (j + 4)))
# plt.tight_layout() gives a warning, as the background ax won't be taken into account,
# but normally the other subplots will be rearranged to nicely fill the figure
plt.tight_layout()
plt.show()

Is it possible to remove the border? [duplicate]

This question already has answers here:
matplotlib border width
(3 answers)
Closed 2 years ago.
Hello I have this code using matplotlib :
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1],[1])
ax.tick_params(axis=u'both', which=u'both', length=0)
plt.show()
But I would like to have this :
I mean I just want to remove the black border.
It it possible ?
Thank you very much !
use ax.spines["top"].set_visible(False) to control visibility of boarders
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1],[1])
ax.tick_params(axis=u'both', which=u'both', length=0)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
plt.show()
output

Way to change only the width of marker in scatterplot but not height?

I want to make a scatterplot with marker type as rectange (not square), such that width is more than height. With the "s" I can control the overall size of the marker but it increases in both dimension.
I can not directly pass height and width as these are unknown properties of scatter.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter(np.arange(1,6), np.random.normal(size=5), marker='s', s=16)
Try the following snippet.
import numpy as np
import matplotlib.pyplot as plt
width = 60
height = 30
verts = list(zip([-width,width,width,-width],[-height,-height,height,height]))
fig, ax = plt.subplots()
ax.scatter(np.arange(1,6), np.random.normal(size=5), marker=(verts,0),s=40)
Here, the argument s changes the size of the scatter. The drawn rectangle keeps the ratio width/height.
Output:
update
Since matplotlib 3.2x, use of (verts, 0) is depreciated. The working code should be changed to
fig, ax = plt.subplots()
ax.scatter(np.arange(1,6), np.random.normal(size=5), marker=verts, s=40)

Matplotlib: shift one series data on the x-axis [duplicate]

This question already has answers here:
How to shift a column in Pandas DataFrame
(9 answers)
Closed 4 years ago.
I have the following code:
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
fig, ax = plt.subplots(2,1, figsize=(10, 5))
plt.suptitle('My Data', x = 0.5, y = 1.0, fontsize = '8')
for i in range(0,2):
l1, = ax[i].plot(data_df['col_A'][101:200] , color = 'black')
l2, = ax[i].plot(data_df['col_B'][101:200], color = 'red')
plt.show()
plt.tight_layout()
And here is an output figure:
I am wondering if we could shift the entire red series to the left by 6 steps?
(I tried:
l2, = ax[i].plot(data_df_new['createvm_duration'][101-6:200-6], color = 'red')
which is not what I want because I want the x-axis ticks remain the same, but re-match of black and red peaks.)
Thanks!
Try shift the column by -6 before indexing it:
ax[i].plot(data_df['col_B'].shift(-6)[101:200], color = 'red')

I want my contourf semi-transparent, but my colorbar not [duplicate]

This question already has answers here:
Partially transparent scatter plot, but with a solid color bar
(2 answers)
Closed 7 years ago.
The colorbar takes the same transparency as the contourf-plot which I've placed over an image.
I can achieve a non-transparent colorbar by adding a fake contourf plot without transparency at the lowest "zorder"-location, but I guess there is a proper way?
This gives me a semi-transparent colorbar:
cs = m.contourf(xv,yv,zi,zorder=4,alpha=0.7,origin="lower")
cbar = m.colorbar(cs,location='right',pad="5%")
You can do it, but there's no particular method devoted to just that. (Perhaps there should be.) Instead, you can manually modify the alpha value of cbar.solids.
For example, let's demonstrate the general problem:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10,10))
fig, ax = plt.subplots()
im = ax.imshow(data, cmap='gist_earth', alpha=0.5)
cbar = fig.colorbar(im)
plt.show()
And then if we change the transparency of cbar.solids:
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10,10))
fig, ax = plt.subplots()
im = ax.imshow(data, cmap='gist_earth', alpha=0.5)
cbar = fig.colorbar(im)
cbar.solids.set(alpha=1)
plt.show()
On a side note, if you were working with a transparent contour instead of contourf, you might want to modify the alpha value of all of cbar.lines, as well.

Categories

Resources