Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在中心显示轴,但将标签保留在左侧_Python_Pandas_Matplotlib - Fatal编程技术网

Python 在中心显示轴,但将标签保留在左侧

Python 在中心显示轴,但将标签保留在左侧,python,pandas,matplotlib,Python,Pandas,Matplotlib,我试图绘制一个以零为中心的分布,因此我想显示y轴脊椎为0,但我想将记号标签本身保持在图形的左侧(即,打印区域之外)。我认为这可以通过勾选参数实现,但标签ft选项似乎将标签保持在中心位置。下面是一个简短的例子: import matplotlib.pyplot as plt import numpy as np np.random.seed(1) vals = np.random.normal(loc=0, scale=10, size=300) bins = range(int(min(va

我试图绘制一个以零为中心的分布,因此我想显示y轴脊椎为0,但我想将记号标签本身保持在图形的左侧(即,打印区域之外)。我认为这可以通过
勾选参数
实现,但
标签ft
选项似乎将标签保持在中心位置。下面是一个简短的例子:

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(1)

vals = np.random.normal(loc=0, scale=10, size=300)
bins = range(int(min(vals)), int(max(vals))+1)

fig, ax = plt.subplots(figsize=(15,5))
ax.hist(vals, bins=bins)

ax.spines['left'].set_position('zero')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

ax.grid(axis='y', which='major', alpha=0.5)

plt.show()
这将为您提供:


我希望标签位于网格线的左端,而不是绘图的中心。

可能不是最佳解决方案,但您可以将左棘设置为不可见,并在0处绘制一条直线:

ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

ax.plot((0,0), (0,ax.get_ylim()[-1]),color='k',linewidth=1)
ax.grid(axis='y', which='major', alpha=0.5)

plt.show()
输出:


一种可能性是指示记号标签使用“轴坐标”表示其x位置,使用“数据坐标”表示其y位置。这意味着更改其
tranform
属性

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms as transforms

np.random.seed(1)

vals = np.random.normal(loc=0, scale=10, size=300)
bins = range(int(min(vals)), int(max(vals))+1)

fig, ax = plt.subplots()
ax.hist(vals, bins=bins)

ax.spines['left'].set_position('zero')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

ax.grid(axis='y', which='major', alpha=0.5)

trans = transforms.blended_transform_factory(ax.transAxes,ax.transData)
plt.setp(ax.get_yticklabels(), 'transform', trans)

plt.show()

第一个主意不错,不过我想我应该用ax.axvline(x=0,color='k',lw=1)来做垂直线,因为它应该更可靠。