In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you about the Python visualization of the line chart is how, the editor thinks it is very practical, so share with you to learn, I hope you can get something after reading this article, say nothing, follow the editor to have a look.
Abstract: when using matplotlib to draw a line chart with horizontal axis as date format, there are many skills. This paper introduces the method of drawing daily line chart with the help of stock data returned by Tushare package.
Review:
Analysis of Python data processing (1): date data processing
The data source drawn by the line chart uses the Tushare package to obtain the basic data table of listed companies in the following format:
1import pandas as pd
2data = pd.read ('get_stock_basics.csv',encoding =' utf8')
3print (data.head ())
four
5ts_code symbol name list_status list_date is_hs
6000001.SZ 1 Ping an Bank L 19910403 S
7000002.SZ 2 Vanke A L 19910129 S
8000004.SZ 4 National Agricultural Science and Technology L 19910114 N
9000005.SZ 5th Century Star Source L 19901210 N
Then use resample and to.period methods to summarize the number of listed companies in each year, in the format of Pandas.Series array.
"summarize the number of listed companies in each year
2data = data.set_index (['list_date'])
3data = data.resample ('AS'). Count () [' ts_code']
4data = data.to_period ('A')
5print (data.head ())
6print (data.tail ())
The results are as follows:
8list_date
91990 7
101991 4
111992 37
121993 106
131994 99
14...
15list_date
162014 124
172015 223
182016 227
192017 438
202018 78
1. Series draws line chart directly
First, we can draw a line chart directly using pandas's array Series:
1import matplotlib.pyplot as plt
2plt.style.use ('ggplot') # sets the drawing style
3fig = plt.figure (figsize = (102.6)) # set the size of the border
4ax1 = fig.add_subplot (1pm 1pm 1)
5data.plot () # draw line chart
six
Setting title and horizontal and vertical axis title
8colors1 ='# 6D6D6D' # set the title color to gray
9plt.title ('changes in the number of listed companies in mainland China over the years', color = colors1,fontsize = 18)
10plt.xlabel ('year')
11plt.ylabel ('quantity (home)')
12plt.show ()
It can be found that there are two problems in the figure: one is the lack of numerical labels, and the other is that the Abscissa years are automatically segmented. We want to be able to add a numerical label, and then the axis shows the annual value of each year. Next, you need to use a new method to redraw the line chart.
two。 The line chart perfects the label to create the x ~ y-axis.
2x = np.arange (0Llen (data), 1)
3 ax1.plot (XMagna data.values, # x, y coordinates
4 color ='# C42022 colors, # line chart color is red
5 marker = 'odyne last markersize = 4 # Mark shape and size setting
6)
7ax1.set_xticks (x) # sets the x-axis label to a sequence of natural numbers
8ax1.set_xticklabels (data.index) # change the x-axis label value to year
9plt.xticks (rotation=90) # rotate 90 degrees so that it is not too crowded
ten
11for XMagna y in zip (XMagne data.values):
12 plt.text (x _ center',color y + 10 ~ m% .0f'% y _ my ha = 'colors1,fontsize = 10)
13 #% .0f'y set label format without decimal
1 "sets the title and the horizontal and vertical axis title
15plt.title ('changes in the number of listed companies in mainland China over the years', color = colors1,fontsize = 18)
16plt.xlabel ('year')
17plt.ylabel ('quantity (home)')
Plt.savefig ('stock.png',bbox_inches =' tight',dpi = 300)
19plt.show ()
The improved line chart is as follows:
As you can see, the x-axis data are displayed year by year and the numerical labels are added.
3. Multivariate line chart
The drawing of a unary line chart is introduced above, and when you need to draw a multivariate line chart, the method is also very simple, as long as you repeat the drawing function. Here we take the binary line chart as an example to draw a comparative line chart of the market capitalization changes of two well-known domestic real estate companies Vanke and Poly Real Estate in 2017.
3.1. Data source
The data source still uses the pro.daily_basic () interface of the tushare package, which returns daily stock market data, including the daily market capitalization total_mv. The two stocks we need to get are 000002.SZ (Vanke) and 600048.SH (Poly). Here's the market capitalization data for 2017.
1import tushare as ts
2ts.set_token ('your token') # can be obtained after registration on the official website.
3pro = ts.pro_api ()
4def get_stock ():
5 lst = []
6 ts_codes = ['000002.SZ,' 600048.SH']
7 for ts_code in ts_codes:
8 data = pro.daily_basic (
9 ts_code=ts_code, start_date='20170101', end_date='20180101')
10 print (lst)
11 reutrn lst
12 # the results are as follows: total_mv is the market value of the day (RMB 10,000):
13 # Vanke Real Estate data
14 ts_code trade_date close... Total_mv circ_mv
150 000002.SZ 20171229 31.06... 3.43E+07 3.02E+07
161 000002.SZ 20171228 30.7... 3.39E+07 2.98E+07
172 000002.SZ 20171227 30.79... 3.40E+07 2.99E+07
183 000002.SZ 20171226 30.5... 3.37E+07 2.96E+07
194 000002.SZ 20171225 30.37... 3.35E+07 2.95E+07
twenty
21 # Poly Real Estate data
22 ts_code trade_date close... Total_mv circ_mv
230 600048.SH 20171229 14.15... 1.68E+07 1.66E+07
241 600048.SH 20171228 13.71... 1.63E+07 1.61E+07
252 600048.SH 20171227 13.65... 1.62E+07 1.60E+07
263 600048.SH 20171226 13.85... 1.64E+07 1.63E+07
274 600048.SH 20171225 13.55... 1.61E+07 1.59E+07
The following is to further modify the data, extract the total_mv column from DataFrame, set index to the date, and then use the resample and pd.to_period methods to summarize the market capitalization data on a monthly basis.
1data ['trade_date'] = pd.to_datetime (data [' trade_date'])
Setting index to date
3data = data.set_index (data ['trade_date']) .sort_index (ascending=True)
"summarize and display by month
5data = data.resample ('m')
6data = data.to_period ()
The market value has been changed to 100 million yuan.
8market_value = data ['total_mv'] / 10000
nine
1the results of the two are as follows: Vanke Real Estate:
112017-01 2291.973270
122017-02 2286.331037
132017-03 2306.894790
142017-04 2266.337906
152017-05 2131.053098
162017-06 2457.716659
172017-07 2686.982164
182017-08 2524.462077
192017-09 2904.085487
202017-10 2976.999550
212017-11 3263.374043
222017-12 3317.107474
2. Poly Real Estate:
242017-01 1089.008286
252017-02 1120.023350
262017-03 1145.731640
272017-04 1153.760435
282017-05 1108.230609
292017-06 1157.276044
302017-07 1244.966905
312017-08 1203.580209
322017-09 1290.706606
332017-10 1244.438756
342017-11 1336.661916
352017-12 1531.150616
3.2. Draw a binary line chart
Using the Series data above, you can make a map.
Set the drawing style
2plt.style.use ('ggplot')
3fig = plt.figure (figsize = (102.6))
4colors1 ='# 6D6D6D' # title color
five
Data1 Vanke, data2 Poly
7data1 = lst [0]
8data2 = lst [1]
Draw the first line chart
10data1.plot (
11color ='# C42022 colors, # line chart color
12marker = 'odyne last markersize = 4, # Mark shape and size settings
13label = 'Vanke'
14)
Draw the second line chart
16data2.plot (
17color ='# 4191C0colors, # line chart color
18marker = 'odyne last markersize = 4, # Mark shape and size settings
19label = 'Poly'
20)
More bars can be drawn in 2 posts.
2. Set the title and the horizontal and vertical axis title
23plt.title ('comparison of market capitalization between Vanke and Poly Real Estate in 2017', color = colors1,fontsize = 18)
24plt.xlabel ('month')
25plt.ylabel ('market capitalization (RMB 100 million)')
26plt.savefig ('stock1.png',bbox_inches =' tight',dpi = 300)
27plt.legend () # display legend
28plt.show ()
The drawing results are as follows:
If you want to add a numeric label, you can use the following code:
Draw the first line chart
Coach creates a label on the x ~ (nd) y axis
3x = np.arange (0Llen (data1), 1)
4ax1.plot (XMagna data1.values, # x, y coordinates
5color ='# C42022 colors, # line chart color red
6marker = 'odyne last markersize = 4, # Mark shape and size settings
7label = 'Vanke'
8)
9ax1.set_xticks (x) # set x-axis label
10ax1.set_xticklabels (data1.index) # sets the x-axis label value
1cm plt.xticks (rotation=90)
12for XMagna y in zip (XMagol data1.values):
13 plt.text (x _ center',color y + 10 ~ m% .0f'% y ~ ha = 'colors1,fontsize = 10)
14 #% .0f'y set label format without decimal
fifteen
Draw the second line chart
17x = np.arange (0Llen (data2), 1)
eighteen
19ax1.plot (XMagna data2.values, # x, y coordinates
20color ='# 4191C0cm, # line chart color blue
21marker = 'odyne last markersize = 4, # Mark shape and size settings
22label = 'Poly'
23)
24ax1.set_xticks (x) # set x-axis label
25ax1.set_xticklabels (data2.index) # sets the x-axis label value
2 plt.xticks (rotation=90)
27for XMagna y in zip (XMeno data2.values):
28 plt.text (x _ center',color y + 10 ~ m% .0f'% y _ my ha = 'colors1,fontsize = 10)
29 #% .0f'y set label format without decimal
thirty
3 setting title and horizontal and vertical axis title
32plt.title ('comparison of market capitalization between Vanke and Poly Real Estate in 2017', color = colors1,fontsize = 18)
33plt.xlabel ('month')
34plt.ylabel ('market capitalization (RMB 100 million)')
thirty-five
36plt.savefig ('stock1.png',bbox_inches =' tight',dpi = 300)
37plt.legend () # display legend
38plt.show ()
The result is shown in the following figure:
It can be seen that the market capitalization of the two stocks has been rising since the beginning of 2017, and Vanke's market capitalization is about twice that of Poly.
The above is what the line chart of Python visualization looks like, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.