matplotlib 在plot python中垂直移动y刻度

5n0oy7gb  于 2023-02-16  发布在  Python
关注(0)|答案(2)|浏览(156)

我有一个直方图,我想垂直移动y刻度(比现有y刻度的位置低0.2 cm)。我搜索了很多,但找不到任何准确的操作。您能帮助我吗?我在这里附上了一张图像,显示了y刻度的新位置。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

VAL = [8, 4, 5, 20]
objects = ['h', 'b', 'c', 'a']
y_pos = np.arange(len(objects))

cmap = plt.get_cmap('RdYlGn_r')
norm = plt.Normalize(vmin=min(VAL), vmax=max(VAL))
ax = sns.barplot(x=VAL, y=objects, hue=VAL, palette='RdYlGn_r', dodge=False)

plt.yticks(y_pos, objects)

plt.show()
huwehgph

huwehgph1#

由于我们希望偏移量随绘图大小而变化,因此最好将偏移量基于y_pos的步长。我们将其存储为dy,然后将其一部分作为偏移量添加到yticks()中。

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

VAL = [8, 4, 5, 20]
objects = ['h', 'b', 'c', 'a']
y_pos = np.arange(len(objects))
dy = y_pos[1] - y_pos[0]

cmap = plt.get_cmap('RdYlGn_r')
norm = plt.Normalize(vmin=min(VAL), vmax=max(VAL))
ax = sns.barplot(x=VAL, y=objects, hue=VAL, palette='RdYlGn_r', dodge=False)

plt.yticks(y_pos + 0.1*dy, objects)

plt.show()
ht4b089n

ht4b089n2#

我认为诀窍在于:

yticks = ax.yaxis.get_ticklocs()
new_yticks = yticks + 0.2
ax.set_yticks(new_yticks)
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

VAL = [8, 4, 5, 20]
objects = ['h', 'b', 'c', 'a']

cmap = plt.get_cmap('RdYlGn_r')
norm = plt.Normalize(vmin=min(VAL), vmax=max(VAL))
ax = sns.barplot(x=VAL, y=objects, hue=VAL, palette='RdYlGn_r', dodge=False)

yticks = ax.yaxis.get_ticklocs()
new_yticks = yticks + 0.2
ax.set_yticks(new_yticks)

plt.show()

相关问题