Can I have two colorbars corresponding to each scatter plot? I don't understand why the second scatter plot creates a second colorbar but uses the colormap of the previous plot.
import pandas as pd
import matplotlib.pyplot as plt
fig = plt.figure(num=1, clear=True)
ax = fig.add_subplot()
d = pd.DataFrame({'a': range(10), 'b': range(10), 'c': range(10)})
e = pd.DataFrame({'a': range(1,11), 'b': range(10), 'c': range(10)})
d.plot.scatter(x='a', y='b', c='c', cmap='GnBu', ax=ax)
e.plot.scatter(x='a', y='b', c='c', cmap='RdPu', ax=ax)
Pandas plotting does a lot of things automatically, but isn't always easy to change afterwards. In this case, pandas doesn't take into account that twice the same ax
is used, and calls plt.colorbar
twice.
If manipulation of the result is desired, it is often easier to create the plot directly with matplotlib. Note that the second colorbar is drawn closest to the plot. Therefore, the order is changed in the code below.
import pandas as pd
import matplotlib.pyplot as plt
fig = plt.figure(num=1, clear=True)
ax = fig.add_subplot()
d = pd.DataFrame({'a': range(10), 'b': range(10), 'c': range(10)})
e = pd.DataFrame({'a': range(1,11), 'b': range(10), 'c': range(10)})
d_scatter = ax.scatter(x=d['a'], y=d['b'], c=d['c'], cmap='GnBu')
e_scatter = ax.scatter(x=e['a'], y=e['b'], c=e['c'], cmap='RdPu')
plt.colorbar(e_scatter)
plt.colorbar(d_scatter)
plt.show()
PS: When there is more than one colorbar, the bars can also be put explicitly into their own subplot. That way the mutual distances can be controlled better. Especially when there would be 3 or more colorbars, things would look ugly otherwise.
import pandas as pd
import matplotlib.pyplot as plt
fig, axes = plt.subplots(ncols=3, gridspec_kw={'width_ratios': [15, 1, 1] })
d = pd.DataFrame({'a': range(10), 'b': range(10), 'c': range(10)})
e = pd.DataFrame({'a': range(1,11), 'b': range(10), 'c': range(10)})
d_scatter = axes[0].scatter(x=d['a'], y=d['b'], c=d['c'], cmap='GnBu')
e_scatter = axes[0].scatter(x=e['a'], y=e['b'], c=e['c'], cmap='RdPu')
plt.colorbar(d_scatter, cax=axes[1])
plt.colorbar(e_scatter, cax=axes[2])
plt.show()