【问题标题】:Change coordinates for origin in scatter plot with centred axes使用中心轴更改散点图中原点的坐标
【发布时间】:2021-04-20 11:56:28
【问题描述】:

我有一些数据集在散点图中进行可视化。我有一堆平均值和全局平均值。我所追求的,但不能真正实现的是,有一个散点图,在图中居中,同时也将原点放在全局平均值上。

这是定义绘图布局的代码:

plt.figure(1)
plt.suptitle('Example')
plt.xlabel('x (pixels)')
plt.ylabel('y (pixels)')
ax = plt.gca()
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.scatter(x_data, y_data, color=color, alpha=0.08, label=csv_file_name)
ax.plot(global_mean[0], global_mean[1], color='green',
            marker='x', label='Global mean')

这会产生以下图(对于每个数据集多次调用 ax.scatter(),但它不在上面的代码中):

我尝试过使用ax.set_position() 参数,但到目前为止没有任何效果。有没有办法用 matplotlib 做我所追求的,还是我需要使用其他一些绘图库?

【问题讨论】:

  • 好吧,我们无法重现这种行为。如果您只是禁用某些轴,为什么所有轴都会消失?如果您移动一个轴或禁用一个轴,它们会消失吗?您可能还想添加有关您的环境的更多信息 - matplotlib、Python、操作系统版本。在这里工作:Win 10 上的 matplotlib 3.3.3、Python 3.8 和 matplotlib 2.0.0 Python 3.6

标签: python matplotlib plot pycharm


【解决方案1】:

您可以使用ax.spines() 方法来移动它们。

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

#generate some random data
x = np.linspace(1,2, 100)
y = [random.random() for _ in range(100)]

fig = plt.figure(figsize=(10,5))

# original plot
ax = fig.add_subplot(1,2,1)
ax.scatter(x, y)

# same plot, but with the spines moved
ax2 = fig.add_subplot(1,2,2)
ax2.scatter(x, y)
# move the left spine (y axis) to the right
ax2.spines['left'].set_position(('axes', 0.5))
# move the bottom spine (x axis) up
ax2.spines['bottom'].set_position(('axes', 0.5))
# turn off the right and top spines
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)

plt.show()

【讨论】:

  • 这是我尝试过的解决方案,但这样做会完全为我移除刺。不确定我的代码中是否还有其他内容可以“覆盖”它。
  • 您是否在 Jupyter notebook、Google Colabs、Spyder 等特定环境中工作,您是否将其命名为让后台的工作“更轻松”?如果是这样,这应该在问题中标记和提及。目前尚不清楚为什么这段代码应该删除所有轴。
  • @Mr.我正在使用 PyCharm,但我不知道它会做类似的事情。
  • 谢谢@Mr.T,你是对的,已经做了必要的编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 2016-08-06
  • 1970-01-01
  • 2016-07-27
相关资源
最近更新 更多