Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to draw a line chart in Matplotlib

Shulou Source: shulou.com Published: 2022-06-02 06:25:28 10月27日 Update

This article shows you how to draw a line chart in Matplotlib, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

I. introduction of matplotlib

Here, we use the stock data of the tushare module as the demonstration data for the drawing

Data = ts.get_hist_data ('sz50',start='2016-11-01)

Data = data.sort_index ()

First, let's draw a basic line chart.

Simply use the plot () method to draw a basic line chart.

To facilitate the following demonstration, let's add a line chart with the highest price to the graph.

After the plot () method, add a method of drawing a line chart, and you can draw a second line in the same graph. It's as simple as that.

But we found two problems, first, the graphics are too small to be easy to view, and second, because the two broken lines are relatively similar, the colors are not easy to distinguish. Next, let's set the size of the graphics and the color of the lines.

Instantiate a figure object and use the parameter figsize to set its size to (16re8), so that the following drawing methods inherit from the properties of the figure object.

Let's solve the second problem, line color.

We use the color property in the plot () method to set the highest price broken line color to red, so that the two broken lines look easy to distinguish.

But such a picture is still too crude, we add the title of the line chart, X-axis information, Y-axis information, legend:

Because the information on the X-axis is a timestamp, here, we use matplotlib.pylab 's datestr2num method to convert the time string into a number, and then draw a line chart through the plot_date () method. The ordinary X-axis information can be set using plt.xticks.

Use the title () method to set the title, the xlable () method to set the X axis description, the ylable () method to set the Y axis description, and the legend () method to set the legend.

In this way, a basic line chart is completed, but it doesn't look very beautiful, so let's beautify it.

Although this looks much better than before, but still feel the picture is very rough, we can try to change the graphic theme.

The above content is how to draw a broken line in Matplotlib. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Method line graph graph information broken line color highest content legend size object namely attribute skill data highest price title knowledge line question Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Apple Xiaomi Shulou Information Linux