Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.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 如何删除与对数刻度轴上的自定义X点对应的特定网格线?_Python_Matplotlib - Fatal编程技术网

Python 如何删除与对数刻度轴上的自定义X点对应的特定网格线?

Python 如何删除与对数刻度轴上的自定义X点对应的特定网格线?,python,matplotlib,Python,Matplotlib,我想删除与自定义xtick对应的垂直网格线(在下图中显示为x=71)。我可以通过使用hack删除下图中与ytick 701相对应的水平网格线:因为我在y轴上没有小记号,所以我将与指向最大值并穿过y轴的线相对应的自定义ytick定义为小记号,然后我禁用了y轴上小记号的网格线。不幸的是,我不能在x轴上使用相同的hack而不禁用次要刻度的网格线,这是我想不惜一切代价避免的事情 下面是一个不太小的问题,尽管我们仍然需要解决 有很多事情我不明白,两个专业是为什么 locs, labels = plt.xt

我想删除与自定义xtick对应的垂直网格线(在下图中显示为x=71)。我可以通过使用hack删除下图中与ytick 701相对应的水平网格线:因为我在y轴上没有小记号,所以我将与指向最大值并穿过y轴的线相对应的自定义ytick定义为小记号,然后我禁用了y轴上小记号的网格线。不幸的是,我不能在x轴上使用相同的hack而不禁用次要刻度的网格线,这是我想不惜一切代价避免的事情

下面是一个不太小的问题,尽管我们仍然需要解决

有很多事情我不明白,两个专业是为什么

locs, labels = plt.xticks() 
不返回绘制的LOC和标签,以及为什么不将xticks标签显示为10^x,其中x=0、1、2和3,但这超出了原始问题的范围

import matplotlib.pyplot as plt
plt.grid(True)
import numpy as np

# Generate data
x_data = np.arange(1, 1000 , 10)
y_data = np.random.lognormal(1e-5, 3, len(x_data))
y_max = max(y_data) 

# plot
plt.xscale('log')
import math
ratio_log = math.log(x_data[np.argmax(y_data)]) / math.log(max(x_data)) # I need to do this in order to plot a horizontal red dashed line that points to the max and do not extend any further.
plt.axhline(y=y_max, xmin=0, xmax = ratio_log, color='r', linestyle='--')  # horizontal line pointing to the max y value. 
axes = plt.gca()
axes.set_xlim([1, max(x_data)]) # Limits for the x axis.

# custom ticks and labels
# First yticks because I'm able to achieve what I seek
axes.set_yticks([int(y_max)], minor=True) # Sets the custom ytick as a minor one.
from matplotlib.ticker import FormatStrFormatter
axes.yaxis.set_minor_formatter(FormatStrFormatter("%.0f"))          
axes.yaxis.grid(False, which='minor') # Removes minor yticks grid. Since I only have my custom yticks as a minor one, this will disable only the grid line corresponding to that ytick. That's a hack.         
import matplotlib.ticker as plticker
loc = plticker.MultipleLocator(base=y_max / 3.3) # this locator puts ticks at regular intervals. I ensure the y axis ticks look ok.
axes.yaxis.set_major_locator(loc)

# Now xticks. I'm having a lot of difficulty here, unable to remove the grid of a particular custom xticks.
locs, labels = plt.xticks() # Strangely, this doesn't return the locs and labels that are plotted. There are indeed 2 values that aren't displayed in the plot, here 1.00000000e-01 and 1.00000000e+04. I've got to remove them before I can append my custom loc and label.

# This means that if I do: plt.xticks(locs, labels) right here, it would enlarge both the lower and upper limits on the x axis... I fail to see how that's intuitive or useful at all. Might this be a bug?
locs = np.append(locs[1:-1], np.asarray(x_data[np.argmax(y_data)])) # One of the ugliest hack I have ever seen... to get correct ticks and labels.
labels = (str(int(loc)) for loc in locs) # Just visuals to get integers on the axis.
plt.xticks(locs, labels) # updates the xticks and labels.
plt.plot((x_data[np.argmax(y_data)], x_data[np.argmax(y_data)]), (0, y_max), 'r--') # vertical line that points to the max. Non OO way to do it, so a bad way.
plt.plot(x_data, y_data)
plt.savefig('grid_prob.png')
plt.close()
下面的示例图片(代码每次执行时都输出不同的图片,但问题出现在所有图片中)


这个想法归功于@ImportanceOfBeingErnest,我非常感谢他

我用手指把网格移走了

axes.xaxis.grid(False, which='both')
,然后我添加了一个对应于每个xtick的网格,除了具有以下循环的自定义网格:

for loc in locs[1:-1]:
    if loc != x_data[np.argmax(y_data)]:
        plt.axvline(x=loc, color = 'grey', linestyle = '-', linewidth = 0.4)                                                                                                            
在行前插入此代码

plt.xticks(locs, labels) # updates the xticks and labels.  
下面是输出图片的示例。

这个问题可能是正确的,但我在理解这个问题时遇到了问题。在我看来,您可以在位置71手动添加网格;然后你问如何移除它。如果根本不显示网格,而是在需要的地方添加一条简单的线,这不是更容易吗?我看不出我在位置71手动添加网格的位置。我看到我用plt.grid(True)启用了网格,这就是我所做的关于x轴网格的所有工作。当然,我添加了xtick,但不是手动添加网格,除非我遗漏了什么。回答你的问题,我不知道。然而,你的评论帮助我解决了这个问题(尽管我做的效率很低)。看看我贴的答案。另外,如果您有更有效的方法来实现相同的结果,例如不使用plt.grid(True)加载网格,或者甚至不使用.set_visible(),我很乐意接受您的答案。我还意识到我只添加了几行代码,使代码更加复杂,因此我可能没有按照您提到的方法解决问题。因此,请随时发布您的解决方案。