In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article is about how Python draws a lollipop chart of its position list. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Demand
Friends who do stock analysis often see a chart of futures companies' positions like this:
This kind of picture is a lollipop chart. That's the goal of our article today:
Draw the lollipop chart of the futures position list.
The two ends of the center line of the picture are dots or diamonds, next to which are marked the position securities firm and the corresponding number of long positions or short positions, and the color of the left and right lines is different. The idea of drawing is: first draw a horizontal line, then use scatter scatter to draw the points on the left and right ends of the line, and then mark the names of both ends, as well as the title and notes.
The two commonly used chart libraries in Python are matplotlib and plotly. The above picture is drawn in matplotlib. Plotly is more interactive.
Further, if you want users to click to select a transaction date and view the list chart corresponding to that date, this can be done through a responsive web application. Dash is an interactive visual web application framework based on python. Both matplotlib and Plotly can be used in conjunction with the Dash framework.
Matplotlib is familiar to everyone. Before we begin, let's briefly introduce plotly and Dash.
2. Plotly
The plotly Library (plotly.py) is an interactive open source drawing library that supports more than 40 unique chart types, covering a variety of statistical, financial, geographical, scientific and 3D use cases. It is an interactive chart library for Python,R and JavaScript.
Plotly.py is built on top of the Plotly JavaScript library (plotly.js), which allows Python users to create beautiful interactive visualization effects based on Web. These visualizations can be displayed in a Jupyter notebook, saved to a separate HTML file, or used as pure Python. Interface descriptions of various icons are provided on its official documentation.
3. Dash
Dash is the Python framework for building Web applications. Dash is based on Flask, Plotly.js and React.js, that is, the controls in Dash and their trigger events are wrapped in React.js. Plotly.js provides a powerful interactive data visualization library for Dash, and Flask provides a back-end framework for it. This framework is particularly friendly to python programmers, only need to write python code, do not need to write JS code, just drag and drop controls to use. If you are interested in children's shoes, you can learn more about the official documents of Dash. Dash is ideal for building data visualization applications with a highly customized user interface using pure Python. It is especially suitable for data analysis, data visualization and dashboard or report presentation. You can deploy Dash applications to a server and then share them through URL, regardless of platform and environment.
4. Installation
Before drawing, we need to install the related packages of Dash and plotly. You can install it with pip:
Pip install plotly dash can also be installed with conda. 5. Data format and data processing
The test data come from Oriental Fortune Network and are saved in csv file format.
The format of the data is as follows, header is the date in the first column, and column 3 is followed by the name of the futures company. The negative number in the table is the blue short position in the above picture, and the positive number is the red long position. When drawing, take a row of records from a certain date from the table, sort the number of positions, store the corresponding data in the list, and then draw.
First of all, the data is cleaned and processed, and the pandas reads the data, where you need to remove the 000905_SH column and delete all zero rows. The code is as follows:
Excel_pd = pd.read_excel ('data/IC futures merchant historical data (1). Xlsx', index_col=' date') # empty excel_pd.dropna () # remove 000905 _ SH column excel _ pd = excel_pd.drop (labels='000905_SH', axis=1) # go to 0 line excel_pd = excel_pd [~ (excel_pd = = 0) .all (axis=1)] # take out the time list and get the maximum and minimum dates Judge for calendar options date_list = excel_pd.index.values.tolist () min_date = min (date_list) max_date = max (date_list)
Next, we need to filter a row of records according to the date entered, take out the short futures company and the long futures company respectively, and eliminate the futures companies with zero positions. The code is as follows:
Def get_data_via_date_from_excel (date): # filter date sheet1_data = excel_ pd.Lock [date] # remove column value: 0 sheet1_data = sheet1_ data [sheet1 _ data! = 0] # sort from small to large sheet1_data = sheet1_data.sort_values () # short position short_hold = sheet1_ data [Sheet1 _ date
< 0] # 多仓 long_hold = sheet1_data[sheet1_data >= 0] .sort values (ascending=False) return short_hold, long_hold6. Draw a picture
Matplotlib drawing
Create a canvas figure and ax layer, and use ax.hlines to draw short and multi-warehouse horizontal lines, respectively. Use ax.scatter to draw the scattered dots on the left and right sides, and use diamond marker. Use plt.text to mark futures companies and positions at both ends of the line. Plt.annotate painting ranking label, set the color and font size respectively.
But this effect is reverse, we want to rank the top at the top and the bottom at the bottom. At this point, we can set the y-axis to reverse ax.invert_yaxis (). Add the legend and title and set the axis invisible to get the final result:
The core code is as follows:
Def draw_lollipop_graph (short_hold, long_hold, date): # sheet_major.index.values.tolist () fig, ax= plt.subplots (figsize= (10,8)) # short position horizontal line ax.hlines (y = [I for i in range (len (short_hold))], xmin=list (short_hold), xmax= [0] * len (short_hold.index), color='#1a68cc' Label=' empty') # Multi-warehouse horizontal line ax.hlines (y = [I for i in range (len (long_hold))], xmax=list (long_hold), xmin= [0] * len (long_hold.index), color='red', label=' duo') # scatter ax.scatter (x=list (short_hold), y = [i for i in range (len (short_hold))], Song10, marker='d', edgecolors= "# 1a68cc", zorder=2 Color='white') # zorder set the point coverage line ax.scatter (x=list (long_hold), y = [i for i in range (len (long_hold))], sq10, marker='d', edgecolors= "red", zorder=2, color='white') # zorder set the point coverage line # draw the line for x, y, label in zip (list (short_hold), range (len (short_hold)), short_hold.index): plt.text (x, y) Format (abs (x)), horizontalalignment='right', verticalalignment='center', fontsize=10) for x, y, label in zip (list (long_hold), range (len (long_hold)), long_hold.index): plt.text (x, y, label+''+ label+' ({}) '.format (abs (x), horizontalalignment='left', verticalalignment='center', fontsize=10) # set ranking size= [17,16] 15] + [8 for i in range (max (len (short_hold), len (long_hold))-3)] color = ['# b91818,'# e26012,'# dd9f10'] + ['# 404040 'for i in range (max (len (short_hold), len (long_hold))-3)] for I, s, c in zip (range (max (len (short_hold), len (long_hold)) + 1), size, color): plt.annotate (s=i+1) Xy= (0, I), fontsize=s, ma='center', ha='center' Color=c) # Axis y inverted ax.invert_yaxis () # Axis not visible ax.set_xticks ([]) ax.set_yticks ([]) ax.spines ['top']. Set_visible (False) # to the upper border ax.spines [' bottom']. Set_visible (False) # to the lower border ax.spines ['left']. Set_visible (False) # Go to the left border ax.spines ['right'] .set_visible (False) # go to the right border # set title ax.set_title (' Golden position Dragon Tiger list ({}) '.format (date)) Position= (0.7,1.07), fontdict=dict (fontsize=20, color='black') # automatically obtain ax legend handle and its label handles, labels= ax.get_legend_handles_labels () plt.legend (handles=handles, ncol=2, bbox_to_anchor= (0.75,1.05), labels=labels, edgecolor='white' Fontsize=10) # Save fig image_filename = "lollipop_rank.png" plt.savefig (image_filename) encoded_image = base64.b64encode (open (image_filename, 'rb'). Read ()) # plt.show () return encoded_image thanks for reading! This is the end of the article on "how to draw a lollipop chart of Python's position list". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.