Matplotlib: impose personalized colorbar - matplotlib

background story:
I am producing two plots. One plot is a standard scatterplot with color map. The other plot contains multiple histograms, each histogram has a different color that is mapped to the colormap of the previous plot. I now want to show the colormap of the previous plot in this new plot. Here is a snippet of code:
#plot 1
f1, ax1 = plt.subplots()
sc = ax1.scatter(x, y, c=z)
cb = f1.colorbar(sc)
f1.show()
#plot 2
f2, ax2 = plt.subplots()
h1 = ax2.hist(x1, color=cb.to_rgba(val1))
h2 = ax2.hist(x2, color=cb.to_rgba(val2))
h3 = ax2.hist(x3, color=cb.to_rgba(val3))
Now I would like to add cb (from the f1 plot) to this new plot. Something like f2.set_colorbar(cb) does not exists.
Question
Given a plot generated with f2, ax2 = plt.subplots() and given a colorbar, how can I force matplotlib to insert a given colorbar in this plot? Note that the colorbar does not need to be related to the data inside the plot

You may simply add another colorbar to the second figure based on the PathCollection of the first figure's scatter plot.
f1, ax1 = plt.subplots()
sc = ax1.scatter(x, y, c=z)
cb = f1.colorbar(sc)
f1.show()
#plot 2
f2, ax2 = plt.subplots()
cb2 = f2.colorbar(sc)

Related

Matplotlib doesn't show both datasets points on the figure when I want to create scatter plot with

I'm sure that I've done all things right but in the end the result I got is a sccatter plot that only shows the second datasets data.
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.scatter(train["ENGINESIZE"], train["CO2EMISSIONS"], color = "green")
ax1.scatter(test["ENGINESIZE"], test["CO2EMISSIONS"], color = "red")
plt.xlabel("Engine Size")
plt.ylabel("Emission")
plt.show()
Here You can see what's going on in my output in link below.
It shows only red data(test data) in the output.
Where is the "output link below", please? For now I can only imagine what you are describing.
Also it helps if both plots have the same axis. That is, both have the same x-axis and then they can vary on their y-axis.
If so:
fig, ax = plt.subplots()
df.plot(kind = 'scatter', x= train["ENGINESIZE"], y = train["CO2EMISSIONS"], color = {'g'}, ax = ax)
df.plot(kind = 'scatter', x= test["ENGINESIZE"], y = test["CO2EMISSIONS"], color = {'r'}, ax = ax)
plt.xlabel()

matplotlib: Controling dimensions in mosaic

I used this code from the documentation to create a mosaic. How do I control the heights of figures individually now?
fig, axs = plt.subplot_mosaic([['a)', 'b)'], ['c)', 'c)']],constrained_layout = True)
for label, ax in axs.items():
# label physical distance to the left and up:
trans = mtransforms.ScaledTranslation(-20/72, 7/72, fig.dpi_scale_trans)
ax.text(0.0, 1.0, label, transform=ax.transAxes + trans,
fontsize='medium', va='bottom', fontfamily='serif')
plt.show()

how to add variable error bars to scatter plot points with shared axes in python matplotlib

I have generated a plot that shows a topographic profile with points along the profile that represent dated points. However, these dated points also have symmetric uncertainty values/error bars (that typically vary for each point).
In this example, I treat non-dated locations as 'np.nan'. I would like to add uncertainty values to the y2 axis (Mean Age) with defined uncertainty values as y2err.
Everytime I use the ax2.errorbar( ... ) line, my graph is squeezed and distorted.
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
#Longitude = x; Elevation = y
x = (-110.75696,-110.75668,-110.75640,-110.75612,-110.75584,-110.75556,-110.75528)
y = (877,879,878,873,871,872,872)
ax1.plot(x, y)
ax1.set_xlabel('Longitude')
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('Elevation', color='b')
ax1.tick_params('y', colors='b')
ax2 = ax1.twinx()
# Mean Age, np.nan = 0.0
y2 = (np.nan,20,np.nan,np.nan,np.nan,np.nan,np.nan)
y2err = (np.nan,5,np.nan,np.nan,np.nan,np.nan,np.nan)
ax2.scatter(x, y2, color='r')
#add error bars to scatter plot points
# (??????) ax2.errorbar(x, y, y2, y2err, capsize = 0, color='black')
ax2.set_ylim(10,30)
ax2.set_ylabel('Mean Age', color='r')
ax2.tick_params('y', colors='r')
fig.tight_layout()
plt.show()
If I do not apply the ax2.errorbar... line my plot looks like the first image, which is what I want but with the points showing uncertainty values (+/- equal on both side of point in the y-axis direction).
Plot of Elevation vs Age without error bars
When I use the ax2.errorbar line it looks like the second image:
Plot when using ax2.errorbar line
Thanks!

Matplotlib Subplot Labels Disappear

I want to prepare some hexbin plots from Pandas. My initial code is:
fig = plt.figure(figsize=(11,8))
ax1 = fig.add_subplot(111)
df2.plot(kind='hexbin', x='var1', y='var2', C='var3', reduce_C_function=np.median, gridsize=25,vmin=0, vmax=40,ax=ax1)
ax1.set_xlim([-5,2])
ax1.set_ylim([0,7])
However when I change this to:
fig = plt.figure(figsize=(11,8))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
And plot create four subplots similar to the first example it turns off the xlabels and xticklabels.
What code to I need to switch them back on? And is this something I can do as a defaults?

matplotlib shared row label (not y label) in plot containing subplots

I have a trellis-like plot I am trying to produce in matplotlib. Here is a sketch of what I'm going for:
One thing I am having trouble with is getting a shared row label for each row. I.e. in my plot, I have four rows for four different sets of experiments, so I want row labels "1 source node, 2 source nodes, 4 source nodes and 8 source nodes".
Note that I am not referring to the y axis label, which is being used to label the dependent variable. The dependent variable is the same in all subplots, but the row labels I am after are to describe the four categories of experiments conducted, one for each row.
At the moment, I'm generating the plot with:
fig, axes = plt.subplots(4, 5, sharey=True)
While I've found plenty of information on sharing the y-axis label, I haven't found anything on adding a single shared row label.
As far as I know there is no ytitle or something. You can use text to show some text. The x and y are in data-coordinates. ha and va are horizontal and vertical alignment, respectively.
import numpy
import matplotlib
import matplotlib.pyplot as plt
n_rows = 4
n_cols = 5
fig, axes = plt.subplots(n_rows, n_cols, sharey = True)
axes[0][0].set_ylim(0,10)
for i in range(n_cols):
axes[0][i].text(x = 0.5, y = 12, s = "column label", ha = "center")
axes[n_rows-1][i].set_xlabel("xlabel")
for i in range(n_rows):
axes[i][0].text(x = -0.8, y = 5, s = "row label", rotation = 90, va = "center")
axes[i][0].set_ylabel("ylabel")
plt.show()
You could give titles to subplots on the top row like Robbert suggested
fig, axes = plt.subplots(4,3)
for i, ax in enumerate(axes[0,:]):
ax.set_title('col%i'%i)