问题
I am using matplotlib to draw a plot. The x and y axises are discrete values and therefore, several (x,y) points in the list have the same values. For example, assume we have the following x,y points:
x=[0,1,1,2,2,2,2,2]
y=[0,1,2,3,3,3,3,5]
Now all of the (x,y) points occur once, but (2,3) occurs 4 times. When I use plt.scatter(x,y), it only shows (2,3) as a regular point, once. How is it possible to show the density of occurrence, too? For example, a bigger marker?
回答1:
You can pass an optional argument s
to plt.scatter
that indicates the size of each point being plotted. To get the size to correspond with the occurrences of each point, first construct a dictionary that count the occurrences, then create a list of the sizes for each point.
import matplotlib.pyplot as plt
from collections import Counter
x=[0,1,1,2,2,2,2,2]
y=[0,1,2,3,3,3,3,5]
# count the occurrences of each point
c = Counter(zip(x,y))
# create a list of the sizes, here multiplied by 10 for scale
s = [10*c[(xx,yy)] for xx,yy in zip(x,y)]
# plot it
plt.scatter(x, y, s=s)
plt.show()
回答2:
Setting the transparency to be smaller than 1 could be one way to visualize this; A more frequent dot will appear darker/less transparent if alpha is smaller than 1:
plt.scatter(x, y, s=80, alpha=0.2)
来源:https://stackoverflow.com/questions/46700733/how-to-have-scatter-points-become-larger-for-higher-density-using-matplotlib