Can I place a vertical colorbar to the left of the

2020-07-18 20:09发布

From the matplotlib command summary for the colorbar method I am aware that the keyword argument orientation := 'horizontal' | 'vertical' as a parameter places an horizontal bar underneath the plot or a vertical to the right of it respectively.

Yet, in my situation, I would rather place the colour bar at the opposite side of the default (without too much fiddling... if possible).

How could I code this? Am I missing some obvious feature?

2条回答
你好瞎i
2楼-- · 2020-07-18 20:33

I've found another method that avoids having to manually edit axes locations, and instead allows you to keep the colorbar linked to an existing plot axis by using the location keyword (method adapted initially from here).

The location argument is meant to be used on colorbars which reference multiple axes in a list (and will throw an error if colorbar is given only one axis), but if you simply put your one axis in a list, it will allow you to use the argument. You can use the following code as an example:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
axp = ax.imshow(np.random.randint(0, 100, (100, 100)))
cb = plt.colorbar(axp,ax=[ax],location='left')
plt.show()

which yields this plot:

plot:

查看更多
够拽才男人
3楼-- · 2020-07-18 20:57

I think the easiest way is to make sure the colorbar is in its own axis. You can adapt from this example:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
axp = ax.imshow(np.random.randint(0, 100, (100, 100)))
# Adding the colorbar
cbaxes = fig.add_axes([0.1, 0.1, 0.03, 0.8])  # This is the position for the colorbar
cb = plt.colorbar(axp, cax = cbaxes)
plt.show()

which results in this:

Matplotlib colorbar on the left side of plot

查看更多
登录 后发表回答