标签归档:scatter

如何在Python中用散点图绘制散点图?

问题:如何在Python中用散点图绘制散点图?

在Python中,使用Matplotlib,如何绘制带有圆的散点图?目标是在已经由绘制的一些彩色磁盘周围绘制空圆scatter(),以便突出显示它们,理想情况下不必重新绘制彩色圆。

我试过了facecolors=None,无济于事。

In Python, with Matplotlib, how can a scatter plot with empty circles be plotted? The goal is to draw empty circles around some of the colored disks already plotted by scatter(), so as to highlight them, ideally without having to redraw the colored circles.

I tried facecolors=None, to no avail.


回答 0

从分散的文档中:

Optional kwargs control the Collection properties; in particular:

    edgecolors:
        The string none to plot faces with no outlines
    facecolors:
        The string none to plot unfilled outlines

请尝试以下操作:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.random.randn(60) 
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()

注意:对于其他类型的地块看到这个帖子的使用markeredgecolormarkerfacecolor

From the documentation for scatter:

Optional kwargs control the Collection properties; in particular:

    edgecolors:
        The string ‘none’ to plot faces with no outlines
    facecolors:
        The string ‘none’ to plot unfilled outlines

Try the following:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.random.randn(60) 
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()

Note: For other types of plots see this post on the use of markeredgecolor and markerfacecolor.


回答 1

这些行得通吗?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

或使用plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

Would these work?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

or using plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')


回答 2

这是另一种方式:这会在当前轴,图或图像等上添加一个圆:

from matplotlib.patches import Circle  # $matplotlib/patches.py

def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ):
    """ add a circle to ax= or current axes
    """
        # from .../pylab_examples/ellipse_demo.py
    e = Circle( xy=xy, radius=radius )
    if ax is None:
        ax = pl.gca()  # ax = subplot( 1,1,1 )
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_edgecolor( color )
    e.set_facecolor( facecolor )  # "none" not None
    e.set_alpha( alpha )

(由于,图片中的圆圈被挤压成椭圆形imshow aspect="auto")。

Here’s another way: this adds a circle to the current axes, plot or image or whatever :

from matplotlib.patches import Circle  # $matplotlib/patches.py

def circle( xy, radius, color="lightsteelblue", facecolor="none", alpha=1, ax=None ):
    """ add a circle to ax= or current axes
    """
        # from .../pylab_examples/ellipse_demo.py
    e = Circle( xy=xy, radius=radius )
    if ax is None:
        ax = pl.gca()  # ax = subplot( 1,1,1 )
    ax.add_artist(e)
    e.set_clip_box(ax.bbox)
    e.set_edgecolor( color )
    e.set_facecolor( facecolor )  # "none" not None
    e.set_alpha( alpha )

(The circles in the picture get squashed to ellipses because imshow aspect="auto" ).


回答 3

在matplotlib 2.0中,有一个名为的参数fillstyle ,可以更好地控制标记的填充方式。就我而言,我已将其与错误栏一起使用,但它可用于一般http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html中的标记

fillstyle接受以下值:[‘full’| “左” | ‘正确’| “底部” | ‘顶部’| ‘没有’]

使用时有两点要牢记fillstyle

1)如果将mfc设置为任何类型的值,它将具有优先权,因此,如果您将fillstyle设置为“ none”,则它不会生效。因此,请避免同时使用mfc和fillstyle

2)您可能想要控制标记的边缘宽度(使用markeredgewidthmew),因为如果标记相对较小且边缘宽度较厚,则标记看起来会像已填充,即使没有。

以下是使用错误栏的示例:

myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue',  mec='blue')

In matplotlib 2.0 there is a parameter called fillstyle which allows better control on the way markers are filled. In my case I have used it with errorbars but it works for markers in general http://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.errorbar.html

fillstyle accepts the following values: [‘full’ | ‘left’ | ‘right’ | ‘bottom’ | ‘top’ | ‘none’]

There are two important things to keep in mind when using fillstyle,

1) If mfc is set to any kind of value it will take priority, hence, if you did set fillstyle to ‘none’ it would not take effect. So avoid using mfc in conjuntion with fillstyle

2) You might want to control the marker edge width (using markeredgewidth or mew) because if the marker is relatively small and the edge width is thick, the markers will look like filled even though they are not.

Following is an example using errorbars:

myplot.errorbar(x=myXval, y=myYval, yerr=myYerrVal, fmt='o', fillstyle='none', ecolor='blue',  mec='blue')

回答 4

基于Gary Kerr的示例,如此处所建议可以使用以下代码创建与指定值相关的空圆:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.markers import MarkerStyle

x = np.random.randn(60) 
y = np.random.randn(60)
z = np.random.randn(60)

g=plt.scatter(x, y, s=80, c=z)
g.set_facecolor('none')
plt.colorbar()
plt.show()

Basend on the example of Gary Kerr and as proposed here one may create empty circles related to specified values with following code:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.markers import MarkerStyle

x = np.random.randn(60) 
y = np.random.randn(60)
z = np.random.randn(60)

g=plt.scatter(x, y, s=80, c=z)
g.set_facecolor('none')
plt.colorbar()
plt.show()

回答 5

因此,我假设您想突出显示符合特定条件的一些要点。您可以使用Prelude的命令对高亮点进行第二次散点图绘制,并用一个空圆进行第一次散点图绘制。确保s参数足够小,以使较大的空圆圈包围较小的填充圆。

另一个选择是不使用散点图,而使用circle / ellipse命令分别绘制补丁。这些位于matplotlib.patches中,是一些有关如何绘制圆形矩形等的示例代码。

So I assume you want to highlight some points that fit a certain criteria. You can use Prelude’s command to do a second scatter plot of the hightlighted points with an empty circle and a first call to plot all the points. Make sure the s paramter is sufficiently small for the larger empty circles to enclose the smaller filled ones.

The other option is to not use scatter and draw the patches individually using the circle/ellipse command. These are in matplotlib.patches, here is some sample code on how to draw circles rectangles etc.


Matplotlib散点图; 颜色作为第三个变量的函数

问题:Matplotlib散点图; 颜色作为第三个变量的函数

我想制作一个散点图(使用matplotlib),其中根据第三个变量对点进行阴影处理。我对此非常了解:

plt.scatter(w, M, c=p, marker='s')

其中w和M是数据点,而p是我要针对其着色的变量。
但是我想用灰度而不是彩色来做。有人可以帮忙吗?

I want to make a scatterplot (using matplotlib) where the points are shaded according to a third variable. I’ve got very close with this:

plt.scatter(w, M, c=p, marker='s')

where w and M are the datapoints and p is the variable I want to shade with respect to.
However I want to do it in greyscale rather than colour. Can anyone help?


回答 0

无需手动设置颜色。相反,请指定灰度颜色图…

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()

或者,如果您希望使用更大范围的颜色图,也可以将cmapkwarg 指定为scatter。要使用其中任何一个的反向版本,只需指定其中_r任何一个的“ ”版本即可。例如,gray_r而不是gray。有几种不同的灰度色彩映射预先制作的(如graygist_yargbinary,等)。

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()

There’s no need to manually set the colors. Instead, specify a grayscale colormap…

import numpy as np
import matplotlib.pyplot as plt

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()

plt.show()

Or, if you’d prefer a wider range of colormaps, you can also specify the cmap kwarg to scatter. To use the reversed version of any of these, just specify the “_r” version of any of them. E.g. gray_r instead of gray. There are several different grayscale colormaps pre-made (e.g. gray, gist_yarg, binary, etc).

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
x = np.random.random(10)
y = np.random.random(10)

plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()

回答 1

在matplotlib中,可以将灰色表示为介于0-1之间的数字值。
例如c = '0.1'

然后,您可以将第三个变量转换为该范围内的值,并使用它为点着色。
在以下示例中,我将点的y位置用作确定颜色的值:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()

In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'

Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:

from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]

color = [str(item/255.) for item in y]

plt.scatter(x, y, s=500, c=color)

plt.show()


回答 2

有时您可能需要根据x值情况精确绘制颜色。例如,您可能有一个包含3种类型的变量和一些数据点的数据框。您想做以下事情,

  • 在RED中绘制对应于物理变量’A’的点。
  • 在BLUE中绘制与物理变量“ B”相对应的点。
  • 在绿色中绘制对应于物理变量“ C”的点。

在这种情况下,您可能必须编写short函数以将x值映射为对应的颜色名称作为列表,然后将该列表传递给plt.scatter命令。

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()

Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

  • Plot points corresponding to Physical variable ‘A’ in RED.
  • Plot points corresponding to Physical variable ‘B’ in BLUE.
  • Plot points corresponding to Physical variable ‘C’ in GREEN.

In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()