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 solve the problem of distance between chart and canvas by Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to solve the distance between chart and canvas by Python". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Python how to solve the gap between the chart and the canvas"!

1. Problem situation

When we use python's matplotlib library for drawing, we may encounter incomplete display of the picture content.

Take the following code as an example:

Import matplotlib.pyplot as pltplt.rcParams ['font.sans-serif'] = [' SimHei'] plt.rcParams ['axes.unicode_minus'] = Falsex = range (9) y = [5.12,5.15,5.13,5.10,5.2,5.25,5.19,5.24,5.31] c = 0.5 * (min (x) + max (x)) d = min (y) + 0.3 * (max (y)-min (y)) plt.plot (x, y) Label=' shares A closing price, closing price, ls='-.', marker='D', lw=2) plt.xticks (x, ['2022-03-27,' 2022-03-28, '2022-03-29,' 2022-03-30, '2022-03-31,' 2022-04-01, '2022-04-04, 2022-04-05, 2022-04-06] Rotation=45) plt.title ('closing sequence chart of a stock') plt.xlabel ('date') plt.ylabel ('price') plt.grid (True) plt.legend () # marks the daily closing price for a, b in zip (x, y): plt.text (a, bang 0.01,'% .1f'% b, ha='center', va='bottom', fontsize=9) plt.annotate ('lowest price', (x [y.index (min (y)]) Min (y)), (x [y.index (min (y))] + 2, min (y) + 0.06), xycoords='data', arrowprops=dict (width=3,headwidth=10,headlength=20, facecolor='g',shrink=0.05), plt.show ()

The image effect is shown in the figure, and the label indicating the date on the x-axis at the bottom of the image is not fully displayed:

Although, some students who know it may tell me that as long as the window is enlarged, it can be displayed completely. That's true. But this can only meet our general needs. If our program needs to automatically generate charts and save them, this method will not work. The image file saved with plt.savefig () is shown in the following figure, which is not what we want:

In such a scenario, the application of the subplots_adjust () method is just right.

2. Overview of plt.subplots_adjust ()

There are six parameters commonly used in the plt.subplots_adjust () method.

The syntax is as follows:

Plt.subplots_adjust (left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

Where left, bottom, right, and top in turn represent the distance between the chart and the edge of the canvas in four directions.

The range of values for each of these four parameters is usually between 0 and 1. It is not so much "spacing" as the "coordinates" of the edge of the image. When using these four parameters, the lower left corner of the canvas is regarded as the coordinate origin, and the width and height of the canvas are regarded as 1. If the parameter value is greater than 1, the loss of the image may occur and the image will move outside the canvas without reporting an error.

And left cannot be greater than or equal to right,bottom cannot be greater than or equal to top, if you violate this point, an error will occur.

Wspace and hspace represent the distance between images in horizontal direction and the distance between images in vertical direction respectively. Its value can be greater than 1, and the specific situation can be debugged to select the appropriate one. These two parameters are used when the canvas has multiple subimages.

3. Case presentation 3.1 single-picture situation

Still using the example in the first part as an example, set the parameter bottom, which represents the distance between the chart and the lower edge, to 0.2.

That is, add a sentence to the above code:

Plt.subplots_adjust (bottom=0.2)

The image effect changes as follows:

3.2 the case of multiple subgraphs

Draw the following four images on the canvas. And set the distance between the top, bottom, left and right and between the images.

Draw a line chart on the upper left and a scatter chart on the upper right

Draw a bar chart on the lower left and a box chart on the lower right.

And set the spacing:

Plt.subplots_adjust (left=0.1, right=0.9, bottom=0.1, top=0.9, wspace=0.3, hspace=0.3)

The code is as follows:

Import matplotlib.pyplot as pltimport numpy as npplt.rcParams ['font.sans-serif'] = [' SimHei'] plt.rcParams ['axes.unicode_minus'] = False# position 221 draw a simple line chart fig = plt.figure (1, facecolor='#33ff99', figsize= (10,6)) ax1 = plt.subplot (221) ax1.set_title (' ax1') ax1.set_facecolor ("orange") ax1.plot ([1,1,0,0,-1,0,1,1-1] ) # position 222 or one horizontal axis is the month Ax2 = plt.subplot ax2.set_title ('ax2') ax2.set_facecolor ("purple") ax2.plot ([January, February, March, April, May, June, July, August, September], [1, 0, 2, 5, 3, 5, 8, 7, 9], ls='' Marker='*') # position 223 draw a bar chart ax3 = plt.subplot (223) ax3.set_title ('ax3') ax3.set_facecolor ("pink") ax3.bar ([' A','B','C','D','E'], height= [200,350,600,540,430] Color='#9900ff') # position 224 draw a box diagram ax4 = plt.subplot (224) ax4.set_title ('ax4') np.random.seed (100) data = np.random.randint (0,100, (4,4)) ax4.set_facecolor ("blue") ax4.boxplot (data, labels= (' Open', 'High',' Low') 'Close')) # add the title ax1.set_title (' line chart') ax2.set_title ('scatter chart') ax3.set_title ('column chart') ax4.set_title ('box chart') plt.subplots_adjust (left=0.1, right=0.9, bottom=0.1, top=0.9, wspace=0.3, hspace=0.3) plt.show ()

The effect of generating an image is as follows:

At this point, I believe you have a deeper understanding of "how to solve the gap between chart and canvas by Python". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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