Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to draw scatter plot with Python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Python to draw a scatter chart", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use Python to draw a scatter chart" bar!

Cut the crap and go straight to the code.

Import matplotlib.pyplot as pltimport numpy as np# 1. The first is to import the package, creating data n = 10x = np.random.rand (n) * "randomly generate x coordinates y = np.random.rand (n) *" between 10 02s and randomly generate y coordinates # 2 between 1002s. Create a figurefig = plt.figure (1) # 3. Set the color color value [optional parameters, you can fill it or not], there are several ways: # colors = np.random.rand (n) # randomly generate 10 color values between 01s, or colors = ['ringing,' baked, 'cased,' gelled, 'baked,' kicking,'m'] # you can set a random number of # 4. Set the area size of the point area value [optional parameter] area = 20*np.arange (1, n = 1) # 5. Set the width of the boundary line of the point [optional] widths = np.arange (n) # 0-9 number # 6. Formally draw scatter plot: scatterplt.scatter (x, y, s=area, c=colors, linewidths=widths, alpha=0.5, marker='o') # 7. Set axis label: xlabel, ylabel# set X axis label plt.xlabel ('X coordinate') # set Y axis label plt.ylabel ('Y coordinate') # 8. Setting diagram title: titleplt.title ('test drawing function') # 9. Set the upper and lower limits of the axis display values: xlim, ylim# set the upper and lower limits of the horizontal axis plt.xlim (- 0.5,2.5) # set the upper and lower limits of the vertical axis plt.ylim (- 0.5,2.5) # 10. Set axis scale: xticks, yticks# set horizontal axis precision scale plt.xticks (np.arange (np.min (x)-0.2, np.max (x) + 0.2, step=0.3)) # set vertical axis precision scale plt.yticks (np.arange (np.min (y)-0.2mm, np.max (y) + 0.2mm) Step=0.3)) # can also be set according to xlim and ylim # set horizontal axis precision scale plt.xticks (np.arange (- 0.5,2.5, step=0.5)) # set vertical axis precision scale plt.yticks (np.arange (- 0.5,2.5, step=0.5)) # 11. Display labels at some points in the graph: annotate# plt.annotate ("(" + str (round (x [2], 2)) + "," + str (round (y [2], 2)) + "), xy= (x [2], y [2]), fontsize=10, xycoords='data') # or plt.annotate (" ({0}, {1}) ".format (round (x [2], 2), round (y [2], 2)), xy= (x [2]) Y [2]), fontsize=10, xycoords='data') # xycoords='data' sets the font size to 1'12. Display text in some places in the figure: textplt.text (round (x [6], 2), round (y [6], 2), "good point", fontdict= {'size': 10,' color': 'red'}) # fontdict sets the text font # Add text to the axes.# 13. Set the display Chinese plt.rcParams ['font.sans-serif'] = [' SimHei'] # to display the Chinese label plt.rcParams ['axes.unicode_minus'] = False # to display the minus sign # 14. Set legend, [note, 'drawing test': be sure to be in an iterable format, such as tuples or lists, otherwise only the first character will be displayed, that is, legend will display incomplete] plt.legend (['drawing test'], loc=2, fontsize=10) # plt.legend (['drawing test'], loc='upper left', markerscale = 0.5, fontsize=10) # this can also be # markerscale:The relative size of legend markers compared with the originally drawn ones.# 15. Save the image savefigplt.savefig ('test_xx.png', dpi=200, bbox_inches='tight', transparent=False) # dpi: The resolution in dots per inch to set the resolution to change the definition # If * True*, the axes patches will all be transparent# 16. Show picture showplt.show ()

Main parameters of scatter:

Def scatter (self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, * * kwargs): "" A scatter plot of * y* vs * x* with varying marker size and/or color. Parameters-x, y: array_like, shape (n,) The data positions. S: scalar or array_like, shape (n,), optional The markersize in points**2. Default is ``rcParams ['lines.markersize'] * * 2``. C: color, sequence, or sequence of color, optional, default:'b 'The marker color. Possible values:-A single color format string. -A sequence of color specifications of length n.-A sequence of n numbers to be mapped to colors using * cmap* and * norm*. -A 2murd array in which the rows are RGB or RGBA. Note that * c * should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. If you want to specify the same RGB or RGBA value for all points, use a 2mi D array with a single row. Marker: `~ matplotlib.markers.MarkerStyle`, optional, default:'o' The marker style. * marker* can be either an instance of the class or the text shorthand for a particular marker. See `~ matplotlib.markers` for more information marker styles. Cmap: `~ matplotlib.colors.Colormap`, optional, default: None A `.Colormap` instance or registered colormap name. * cmap* is only used if * c * is an array of floats. If ``None``, defaults to rc ``image.cmap``. Alpha: scalar, optional, default: None The alpha blending value, between 0 (transparent) and 1 (opaque). Linewidths: scalar or array_like, optional, default: None The linewidth of the marker edges. Note: The default * edgecolors* is' face'. You may want to change this as well. If * None*, defaults to rcParams ``lines.linewidth``.

Set legend, [Note, 'drawing Test': be sure to be in an iterable format, such as tuples or lists, otherwise only the first character will be displayed, that is, legend will not be fully displayed]

Plt.legend (['drawing test'], loc=2, fontsize = 10) # plt.legend (['drawing test'], loc='upper left', markerscale = 0.5, fontsize = 10) # this can also be # markerscale:The relative size of legend markers compared with the originally drawn ones.

The parameter loc corresponds to:

Running result:

Supplement

In addition to two-dimensional scatter plots, Python can also draw three-dimensional scatter plots, the following sample code

Import matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np # Random seed np.random.seed (1) def randrange (n, vmin, vmax):''evenly distribute the data (vmin, vmax). '' Return (vmax-vmin) * np.random.rand (n) + vmin fig = plt.figure () ax = fig.add_subplot (111111projection='3d') # can be plotted n = 500for each set of style and range settings, x in [235,332], y in [0100], # z in [zlow] Draw n random points for m, zlow, zhigh in in the box defined in zhigh]: xs = randrange (n, 23,32) ys = randrange (n, 0,100) zs = randrange (n, zlow, zhigh) ax.scatter (xs, ys, zs) Marker=m) # drawing # labels ax.set_xlabel ('X Label') ax.set_ylabel ('Y Label') ax.set_zlabel ('Z Label') plt.show () for X, Y, Z

Output result:

Thank you for your reading, the above is "how to use Python to draw scatter plot" content, after the study of this article, I believe you on how to use Python to draw scatter plot this problem has a deeper understanding, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report