{"id":2857,"date":"2021-04-19T05:25:29","date_gmt":"2021-04-19T05:25:29","guid":{"rendered":"https:\/\/www.tejwin.com\/en\/insights\/matplotlib\/"},"modified":"2021-04-19T05:25:29","modified_gmt":"2021-04-19T05:25:29","slug":"matplotlib","status":"publish","type":"insight","link":"https:\/\/www.tejwin.com\/en\/insights\/matplotlib\/","title":{"rendered":"Matplotlib"},"content":{"rendered":"<p class=\"wp-block-paragraph\">A plot is better than countless words<\/p>\n<figure class=\"wp-block-image size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" alt=\"\" class=\"wp-image-15583\" height=\"560\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/image-223.png\" width=\"840\"\/><\/figure>\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\" id=\"52bf\">After two weeks of some complicated articles, let\u2019s take a break and turn to our previous topic<strong>\u00a0\u201cData Analysis\u201d\u00a0<\/strong>and introduce another important tool when working on the data analysis-<strong>\u00a0data visualization!<\/strong><\/p>\n<p class=\"wp-block-paragraph\" id=\"a3d8\">If you forget what we have done few weeks ago, you can go back, review on them and come back again~~<\/p>\n<\/blockquote>\n<h2 class=\"wp-block-heading\" id=\"70d2\"><strong>Highlights of this article <\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li>Matplotlib Intro\/Application<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"5f9d\"><strong>Links related to this article<\/strong><\/h2>\n<ul class=\"wp-block-list\">\n<li>1\ufe0f\u20e3 API Official Website:\u00a0<a href=\"https:\/\/api.tej.com.tw\/\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ API Official Website<\/strong><\/a><\/li>\n<li>2\ufe0f\u20e3 The Product Package:\u00a0<a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_caseIntro\/1\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ E SHOP<\/strong><\/a><\/li>\n<li>3\ufe0f\u20e3 Source Code:\u00a0<a href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_DataAnalysis\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ GITHUB<\/strong><\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"27f6\">What is the difference between Matplotlib and other packages?<\/h2>\n<p class=\"wp-block-paragraph\" id=\"0801\">There are many packages that could be used in Python to do the data visualization. In addition to Matplotlib,<strong>\u00a0there are other packages to plot such as plotly, seaborn, cufflinks, etc.<\/strong>\u00a0The logic and syntax are similar when working on those packages, but\u00a0<strong>because the connection between Matplotlib and pandas is relatively closer,<\/strong>\u00a0we will use it for the introduction in this article.<br \/><strong>If you want to read the whole document of Matplotlib, you could go through this link:\u00a0<\/strong><a href=\"https:\/\/matplotlib.org\/\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>Matplotlib<\/strong><\/a><strong>\ud83d\udc4d\ud83d\udc4d<\/strong><\/p>\n<h2 class=\"wp-block-heading\" id=\"0135\">How to use Matplotlib?<\/h2>\n<p class=\"wp-block-paragraph\" id=\"744f\">Let\u2019s code step by step!<\/p>\n<h2 class=\"wp-block-heading\" id=\"fa6a\">Data Collecting(TEJAPI)<\/h2>\n<p class=\"wp-block-paragraph\" id=\"8659\">We first get the stock price data of TSMC(2330) and UMC(2303) from the TEJ API.<\/p>\n<pre class=\"wp-block-code\"><code>import tejapi\ntejapi.ApiConfig.api_key = \"your key\"\nTSMC = tejapi.get(\n    'TWN\/EWPRCD', \n    coid = '2330',\n    mdate={'gte':'2020-06-01', 'lte':'2021-04-12'}, \n    opts={'columns': ['mdate','open_d','high_d','low_d','close_d', 'volume']}, \n    paginate=True\n    )\nUMC = tejapi.get(\n    'TWN\/EWPRCD', \n    coid = '2303',\n    mdate={'gte':'2020-06-01', 'lte':'2021-04-12'},\n    opts={'columns': ['mdate','open_d','high_d','low_d','close_d', 'volume']}, \n    paginate=True\n    )\nUMC = UMC.set_index('mdate')\nTSMC = TSMC.set_index('mdate')<\/code><\/pre>\n<h2 class=\"wp-block-heading\" id=\"afb9\">Basic Plotting (Single-Axis, Dual-Axis, Scatter, Histogram, Box)<\/h2>\n<p class=\"wp-block-paragraph\" id=\"e8c2\"><strong>* Single-Axis Plot<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>TSMC['5_MA'] = TSMC['close_d'].rolling(5).mean()\nplt.figure(figsize = (10, 6))\nplt.plot(TSMC['close_d'], lw=1.5, label = 'Stock Price') \nplt.plot(TSMC['5_MA'], lw=1.5, label = '5-Day MA')\nplt.legend(loc = 0)                                        \nplt.xlabel('Date')                                       \nplt.ylabel('Stock Price')\nplt.title('TSMC Stock Price vs 5-Day MA')\nplt.grid()\nplt.show()<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1qehaPaKcGNNPe1rQ4Exk7Q.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"d7db\"><strong>Introduction of different functions:<\/strong><\/p>\n<p class=\"wp-block-paragraph\" id=\"cf6b\"><strong>plt.plot()<\/strong>: Set the information of the plot such as length of width, color, name, etc.<br \/><strong>plt.figure(figsize = (10,6))<\/strong>: Size of the plot<br \/><strong>plt.legend()<\/strong>: Location of the legend<br \/><strong>plt.grid()<\/strong>: Add the grid<br \/><strong>plt.xlabel()<\/strong>: Name of X axis<br \/><strong>plt.ylabel()<\/strong>: Name of Y axis<br \/><strong>plt.title()<\/strong>: Name of title<\/p>\n<p class=\"wp-block-paragraph\" id=\"4c2c\"><strong>* Dual-Axis Plot<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>fig, ax1 = plt.subplots(figsize=(10,8))\nplt.plot(TSMC['close_d'], lw=1.5, label = '2330.TW')                                       \nplt.xlabel('Date')\nplt.ylabel('Stock Price')\nplt.title('TSMC VS UMC Stock Price')\nplt.legend(loc=1)\nax2 = ax1.twinx()\nplt.plot(UMC['close_d'], lw=1.5, color = \"r\",label = '2303.TW')                       \nplt.ylabel('Stock Price')\nplt.legend(loc=2)\nplt.show()\n<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/13NKdZGdtmBvwOCLDnaUckQ.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"3ad6\">There is often a need for dual-axis plots because it is not convenient for reading if the units or magnitudes of the 2 data are different and placed on the same axis.<\/p>\n<p class=\"wp-block-paragraph\" id=\"4b6f\">We use\u00a0<strong>fig, ax1 = plt.subplots() and ax2 = ax1.twinx()<\/strong>\u00a0to generate the second chart but\u00a0<strong>share the X-axis of the first chart.\u00a0<\/strong>It could be understood as making two pictures with exactly the same unit on the X-axis and then stack them up!<\/p>\n<p class=\"wp-block-paragraph\" id=\"ccf5\"><strong>* Scatter Plot, Histogram, and Box Plot<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>##Scatter Plot\nfrom sklearn.linear_model import LinearRegression\nplt.figure(figsize = (10, 6))\nplt.scatter(TSMC['close_d'], UMC['close_d'], color = 'navy')\n##Regression Line\nreg = LinearRegression().fit(np.array(TSMC['close_d'].tolist()).reshape(-1,1),  UMC['close_d'])\npred = reg.predict(np.array(TSMC['close_d'].tolist()).reshape(-1,1))\nplt.plot(TSMC['close_d'], pred, linewidth = 2, color = 'r',label = '\u8ff4\u6b78\u7dda')\nplt.xlabel('TSMC')\nplt.ylabel('UMC')\nplt.title('TSMC vs UMC')\nplt.show()\n<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1NvvuLCrV3sNSi7t5Qzg8_g.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"da86\">First, let\u2019s introduce the scatter plot. It could be used\u00a0<strong>to see the relationship between the two data<\/strong>. If we use the regression line at the same time, the correlation between the two data will be more easily observed.<\/p>\n<pre class=\"wp-block-code\"><code>##Histogram\nret_tsmc = np.log(TSMC['close_d']\/TSMC['close_d'].shift(1)).tolist()\nplt.figure(figsize = (10, 6))\nplt.hist(ret_tsmc, bins = 25)\nplt.xlabel('Log Return')\nplt.ylabel('Frequency')\nplt.title('Log Return vs Frequency')\nplt.show()<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/18-YdrhYxh9MeQXFk3T0c2Q.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"eb53\">Second, let\u2019s introduce the histogram. We can\u00a0<strong>use the histogram to<\/strong>\u00a0<strong>understand the distribution and the frequencies of the yearly log return.<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>##Box Plot\nrv = np.random.standard_normal((1000,2))\nplt.figure(figsize = (10, 6))\nplt.boxplot(rv)\nplt.xlabel('dataset')\nplt.ylabel('value')\nplt.title('ramdon variable box plot')\nplt.show()<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/12o3uSd45wUT4tNj9sBUtUA.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"f721\">The last is the box plot, which could be used to display the statistical characteristics of the dataset and\u00a0<strong>compare multiple datasets at the same time.<\/strong><\/p>\n<h2 class=\"wp-block-heading\" id=\"7ffe\">Financial Time-Series Data Plotting<\/h2>\n<p class=\"wp-block-paragraph\" id=\"7c48\">Let\u2019s combine the plot we\u2019ve mentioned above with the financial data!<\/p>\n<p class=\"wp-block-paragraph\" id=\"597b\"><strong>* Data Collecting<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>tickers = ['2330', '1301', '2317', '2454' , '2882']\ndf  =  tejapi.get(\n        'TWN\/EWPRCD', \n        coid = tickers,\n        mdate={'gte':'2020-06-01', 'lte':'2021-04-12'}, \n        opts={'columns': ['mdate', 'coid','close_d']}, \n        paginate=True\n        )\ndf = df.sort_values(['coid', 'mdate']).set_index('mdate')\ndata = df.pivot_table(index = df.index, columns = 'coid', values = 'close_d')\ndata\n<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1mBCvlwzteXdUnsJYGPPzIw.png\"\/><figcaption class=\"wp-element-caption\">Historical Stock Price DataFrame<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\" id=\"c112\"><strong>*Pandas built-in statistical function<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>data.describe()<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1IuJ7oPVws8WPjWbugIH1oQ.png\"\/><figcaption class=\"wp-element-caption\">Descriptive Statistics<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\" id=\"b58a\">We can use Pandas to present the descriptive statistics of the underlying assets\u00a0<strong>with one-line code!<\/strong>\u00a0It is really a clear and convenient way to process the data!!<\/p>\n<p class=\"wp-block-paragraph\" id=\"2c16\"><strong>* Pandas built-in plotting<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>##Average Rate of Return \ndata.pct_change().mean().plot(kind = 'bar', figsize=(10,6))<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1Fc2MciriBuj8NVr4exz9tw.png\"\/><figcaption class=\"wp-element-caption\">Average Rate of Return<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\" id=\"c53d\">We can directly use the pandas to plot what we want. Isn\u2019t it very convenient?<\/p>\n<pre class=\"wp-block-code\"><code>##Cumulative Log Return\nret = np.log(data\/data.shift(1))\nret.cumsum().apply(np.exp).plot(figsize = (10,6))<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1mT8vBPDtKBnRh-QKwwlt-g.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"e45f\">We use the<strong>\u00a0DataFrame + the apply\u00a0<\/strong>method to perform cumsum() function on the data after the log has been taken, and then perform np.exp() on the result in order to find the cumulative log return.<\/p>\n<pre class=\"wp-block-code\"><code>##High\/Low\/Avg\nwindows = 20\ndata['min'] = data['2330'].rolling(windows).min()\ndata['mean'] = data['2330'].rolling(windows).mean()\ndata['max'] = data['2330'].rolling(windows).max()\nax = data[['min', 'mean', 'max']].plot(figsize = (10, 6), style=['g--', 'r--', 'g--'], lw=1.2)\ndata['2330'].plot(ax=ax, lw=2.5)<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter caption-align-center\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1fmjwzfX2aq2YkdrJe2wozA.png\"\/><figcaption class=\"wp-element-caption\">TSMC 20 Days High, Low and Avg Price<\/figcaption><\/figure>\n<p class=\"wp-block-paragraph\" id=\"e5eb\">Here we use the same concept to find out the 20 days high, low, and the average price of TSMC, and\u00a0<strong>style = [\u2018g- -\u2019] to indicate the color and line presentation mode.<\/strong><\/p>\n<pre class=\"wp-block-code\"><code>##Technical Analysis\n##Long-short term moving avg.\ndata['SMA_5'] = data['2330'].rolling(window = 5).mean()\ndata['SMA_20'] = data['2330'].rolling(window = 20).mean()\ndata[['2330', 'SMA_5', 'SMA_20']].plot(figsize = (10,6))\nata.dropna(inplace = True)\ndata['Positions'] = np.where(data['SMA_5'] &gt; data['SMA_20'], 1, -1)\nax = data[['2330', 'SMA_5', 'SMA_20', 'Positions']].plot(figsize = (10, 6), secondary_y = 'Positions')\n<\/code><\/pre>\n<figure class=\"wp-block-image aligncenter\"><img decoding=\"async\" alt=\"\" src=\"https:\/\/www.tejwin.com\/en\/wp-content\/uploads\/2026\/08\/1iHDVKkPaSNhDRue_MqBw-w.png\"\/><\/figure>\n<p class=\"wp-block-paragraph\" id=\"5aee\">Finally, with the application of a little technical analysis, we can find the long-short term moving averages and the intersection through np.where() function. Therefore, it could be seen that when the\u00a0<strong>Position changes from 1 to -1, the trading signal point is generated.<\/strong><\/p>\n<h2 class=\"wp-block-heading\" id=\"f4a2\">Conclusion<\/h2>\n<p class=\"wp-block-paragraph\" id=\"ea4a\">There are multiple ways to display the plots. We can only introduce the most basic methods here. If you have a high interest in plotting, you could do like explore more application websites or read documents of those packages~<br \/>Then, we will\u00a0<strong>go further into financial data analysis and applications in the next article<\/strong>, please look forward to it \u2757\ufe0f\u2757\ufe0f<\/p>\n<p class=\"wp-block-paragraph\" id=\"0dc2\">Finally, if you like this topic, please click \ud83d\udc4f below, giving us more support and encouragement. Additionally, if you have any questions or suggestions, please leave a message or email us, we will try our best to reply to you.\ud83d\udc4d\ud83d\udc4d<\/p>\n<h2 class=\"wp-block-heading\" id=\"7069\">Links related to this article again!<\/h2>\n<ul class=\"wp-block-list\">\n<li><strong>1\ufe0f\u20e3 API Official Website:\u00a0<\/strong><a href=\"https:\/\/api.tej.com.tw\/\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ API Official Website<\/strong><\/a><\/li>\n<li><strong>2\ufe0f\u20e3 The Product Package:\u00a0<\/strong><a href=\"https:\/\/eshop.tej.com.tw\/E-Shop\/Edata_caseIntro\/1\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ E-SHOP<\/strong><\/a><\/li>\n<li><strong>3\ufe0f\u20e3 Source Code:\u00a0<\/strong><a href=\"https:\/\/github.com\/tejtw\/TEJAPI_Python_Medium_DataAnalysis\" rel=\"noreferrer noopener\" target=\"_blank\"><strong>TEJ GITHUB<\/strong><\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>A plot is better than countless words After two weeks of some complicated articles, let\u2019s take a break and turn to our previous topic\u00a0\u201cData Analysis\u201d\u00a0and introduce another important tool when working on the data analysis-\u00a0data visualization! If you forget what we have done few weeks ago, you can go back, review on them and come [\u2026]<\/p>\n","protected":false},"featured_media":2845,"template":"","tags":[65,70],"insight_category":[16],"class_list":["post-2857","insight","type-insight","status-publish","has-post-thumbnail","hentry","tag-python","tag-tej-api","insight_category-quant-data-science"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight\/2857","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight"}],"about":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/types\/insight"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media\/2845"}],"wp:attachment":[{"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/media?parent=2857"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/tags?post=2857"},{"taxonomy":"insight_category","embeddable":true,"href":"https:\/\/www.tejwin.com\/en\/wp-json\/wp\/v2\/insight_category?post=2857"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}