Specifying matplotlib scatter size in plot units

*爱你&永不变心* 提交于 2019-12-02 15:34:31

问题


I would like to specify my scatter dot size not using points or pixels but rather using plot units. Take for instance the following:

import matplotlib.pyplot as plt
x = [0]
y = [0]
plt.scatter(x,y)
plt.show()

This produces a plot as follows:

What if, say, I wanted my marker to have a radius of exactly 0.002 plot units? I understand the s parameter indicates the area of the marker size in points. Is there a way to directly provide it in plot units? If not what is the best way to convert from plot units to points so I can pass it into the s parameter?

I have also seen some other questions which propose using a PatchCollection and simply plotting a circle with a specified radius. I would prefer not to use this approach. I'd like to avoid extensively rewriting existing code and instead use the s parameter along with plt.scatter. Thanks.

EDIT

I tried using the code from this question which apparently allows you to control the marker size based on plot units. However I couldn't really get it to work for my basic case:

import matplotlib.pyplot as plt
import numpy as np


class scatter():
    def __init__(self,x,y,ax,size=1,**kwargs):
        self.n = len(x)
        self.ax = ax
        self.ax.figure.canvas.draw()
        self.size_data=size
        self.size = size
        self.sc = ax.scatter(x,y,s=self.size,**kwargs)
        self._resize()
        self.cid = ax.figure.canvas.mpl_connect('draw_event', self._resize)

    def _resize(self,event=None):
        ppd=72./self.ax.figure.dpi
        trans = self.ax.transData.transform
        s =  ((trans((1,self.size_data))-trans((0,0)))*ppd)[1]
        if s != self.size:
            self.sc.set_sizes(s**2*np.ones(self.n))
            self.size = s
            self._redraw_later()

    def _redraw_later(self):
        self.timer = self.ax.figure.canvas.new_timer(interval=10)
        self.timer.single_shot = True
        self.timer.add_callback(lambda : self.ax.figure.canvas.draw_idle())
        self.timer.start()


x = [0]
y = [0]
fig = plt.figure()
ax = fig.gca()
size = 3.14*0.002**2
scatter(x, y, ax, size = 0.002, edgecolors = 'black')
ax.set_ylim(-0.004, 0.004)
ax.set_xlim(-0.004, 0.004)
ax.scatter(x,y)
ax.grid()
plt.show()

The above outputs the following figure:

Which does not look like it has a size of 0.002 as I indicated in scatter(x, y, ax, size = 0.002, edgecolors = 'black'). I'm not sure what I'm doing wrong here...

来源:https://stackoverflow.com/questions/57543182/specifying-matplotlib-scatter-size-in-plot-units

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!