英文:
Move the ytick vertically in plot python
问题
我有一个直方图图表,想要垂直移动yticks(比现有yticks位置低0.2厘米)。
我搜索了很多,找不到确切实现这个的方法。你能帮我吗?我在这里附上了一个图像,显示了yticks的新位置。
英文:
I have a histogram plot and I want to move the yticks vertically (0.2 cm lower than their positions of the existing yticks).
I searched a lot and I could not find anything which exactly did this. Could you please help me with that? I attached an image here that shows the new location of the y ticks.
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()
答案1
得分: 1
由于我们希望偏移量随绘图大小而变化,最好基于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()
英文:
Since we want the offset to scale with plot size, it's best to base the offset on the step-size of y_pos. We store that as dy
and then add a fraction of it as an offset in 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()
答案2
得分: 0
我认为关键是:
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()
英文:
I think the trick is:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论