绘图边缘上的标记在 matplotlib 中被切断 [英] Markers on plot edges cut off in matplotlib

查看:34
本文介绍了绘图边缘上的标记在 matplotlib 中被切断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用matplotlib绘制散点图.如果我想使用任何类型的标记,matplotlib 的默认绘图行为会切断图左侧标记的左半部分,以及图右侧标记的右侧.我一直在寻找在不添加额外刻度标签的情况下向绘图的左侧和右侧添加一些额外空间的最自动方法,因此我的标记不会被切断,而且看起来也没有 x-tick 标签不对应任何点.

I want to make a scatter plot using matplotlib. If I want to use any kind of marker the default plotting behavior of matplotlib cuts off the left half of the marker on the left side of the plot, and the right side of the marker on the right side of the plot. I was looking for the most automatic way of adding some extra space to the left and right side of the plot without adding extra tick labels, so my markers aren't cut off and it also doesn't look like there are x-tick labels that don't correspond to any points.

from matplotlib import pyplot as plt
import numpy as np
xx = np.arange(10)
yy = np.random.random( 10 )
plt.plot(xx, yy, 'o' )

此代码生成的图形如下:

This code results in a graph that looks like this:

我想要 x = 0 和 x = 4.5 处的完整圆圈,但我不想要更多刻度标签,我希望代码尽可能简短和自动.

I'd like full circles at x = 0 and x = 4.5, but I don't want any more tick labels, and I'd like to be the code to be as short and automatic as possible.

推荐答案

您将不得不编写一些代码来执行此操作,但您无需事先了解有关数据的任何信息.换句话说, xx 可以更改,并且仍然可以按您期望的那样工作(我认为).

You will have to write some code to do this, but you wont need to know anything about your data in advance. In other words, xx can change and this still will work as you expect (I think).

基本上,您会喜欢您拥有的 x-tick 标签,但您不喜欢这些限制.因此,将代码写入

Basically you'd like the x-tick labels that you have, but you don't like the limits. So write code to

  1. 保存刻度,
  2. 调整限制,以及
  3. 恢复旧的刻度线.

<小时>

from matplotlib import pyplot as plt
import numpy as np
xx = np.arange(10)
np.random.seed(101)
yy = np.random.random( 10 )
plt.plot(xx, yy, 'o' )
xticks, xticklabels = plt.xticks()
# shift half a step to the left
# x0 - (x1 - x0) / 2 = (3 * x0 - x1) / 2
xmin = (3*xticks[0] - xticks[1])/2.
# shaft half a step to the right
xmax = (3*xticks[-1] - xticks[-2])/2.
plt.xlim(xmin, xmax)
plt.xticks(xticks)
plt.show()

结果如下图:

如您所见,y 值存在相同的问题,您可以按照相同的步骤进行更正.

As you can see, you have the same issue for the y values, which you can correct following the same procedure.

另一个选择是使用 clip_on 关键字来关闭行的剪辑: plt.plot(xx,yy,'o',clip_on = False):

Another option is turning off the clipping of the line, using the clip_on keyword: plt.plot(xx, yy, 'o', clip_on=False):

现在圆就在边缘,但它们没有被剪裁并延伸超过轴的框架.

Now the circles are right at the edge, but they are not clipped and extend past the frame of the axes.

这篇关于绘图边缘上的标记在 matplotlib 中被切断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆