You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib子图中偏移分类数据点标记至刻度左右

Matplotlib子图散点标记偏移问题

我曾通过transforms.ScaledTranslation方法在单图中实现散点标记的左右偏移,核心代码如下:

offset = lambda p: transforms.ScaledTranslation(p/72.,0, plt.gcf().dpi_scale_trans)
trans = plt.gca().transData
sc1 = plt.scatter(year, values[:,0], c = 'blue', s = 25, transform=trans+offset(-5))

但将该方法应用到Matplotlib子图时,出现了大量空白图或标记随机散落的问题。以下是可复现的完整代码:

#Libraries needed
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)
import matplotlib.transforms as transforms

#Set up data for reproducible example
year = np.random.choice(np.arange(2006,2017), size=(100) ) 
values1 = np.random.rand(100, 3)
values2 = np.random.rand(100, 3)
values3 = np.random.rand(100, 3)
values4 = np.random.rand(100, 3)
values5 = np.random.rand(100, 3)
values6 = np.random.rand(100, 3)
values7 = np.random.rand(100, 3)
values8 = np.random.rand(100, 3)
data = [values1, values2, values3, values4]
data2= [values5, values6, values7, values8]

#Create plot and set up subplot ax loop
fig, ax = plt.subplots(2,2, figsize = (18,14))
axx = 0, 0, 1, 1
axy = 0, 1, 0, 1

#Set up offset with transform
offset = lambda p: transforms.ScaledTranslation(p/72.,0, plt.gcf().dpi_scale_trans)
trans = plt.gca().transData

#Plot data in a loop
for n, p, q, r in zip(axx, axy, data, data2):
    ax[n,p].plot(year, q, marker='.', ls=' ', ms=10, c = 'b')
    ax[n,p].plot(year, r, marker='.', ls=' ', ms=10, c = 'g')
    
plt.show()

当给绘图函数添加transform参数后,输出直接变为空白:

#Plot data in a loop
for n, p, q, r in zip(axx, axy, data, data2):
    ax[n,p].plot(year, q, marker='.', ls=' ', ms=10, c = 'b', transform=trans+offset(-5))
    ax[n,p].plot(year, r, marker='.', ls=' ', ms=10, c = 'g', transform=trans+offset(5))
    
plt.show()

我研究了transform参数的相关内容但未找到解决方案,请问有更好的实现方法吗?


内容的提问来源于stack exchange,提问作者Bojan Milinic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:30:46