<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yefeng Xia on Medium]]></title>
        <description><![CDATA[Stories by Yefeng Xia on Medium]]></description>
        <link>https://medium.com/@yefengxia?source=rss-2b9554572002------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sa3TkN6jv8oeEdJSFIWwqA.jpeg</url>
            <title>Stories by Yefeng Xia on Medium</title>
            <link>https://medium.com/@yefengxia?source=rss-2b9554572002------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:53:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yefengxia/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dunhuang — a brief Art  Guide]]></title>
            <link>https://medium.com/plain-plan/dunhuang-a-brief-art-guide-bdc9014e3e78?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc9014e3e78</guid>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[china]]></category>
            <category><![CDATA[history]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[ancient-history]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 07:36:11 GMT</pubDate>
            <atom:updated>2023-07-16T07:36:11.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dunhuang — a brief Art Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2VflslGzZJKqK3v7vaTDow.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/es/@realdadalan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">dadalan real</a> on <a href="https://unsplash.com/s/photos/dunhuang?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Dunhuang (敦煌), an oasis on China’s ancient Silk Road, is situated in the northwest of China, where the Gobi Desert and the far eastern edge of the Taklamakan Desert region meet in Gansu Province. Not only is its location worth bragging about, the city’s name is as grand as its historical significance. The name “Dunhuang” (“敦煌”) was given in the Han Dynasty. In Chinese “Dun” (敦) means grandness and “Huang” (煌) means prosperity.</p><p>The ancient town lies at the western end of the Hexi Corridor, which used to be an important stop-over point on the Silk Road. However, nowadays it’s a vestige of the Silk Road, where caravanserai teamed with merchants and Bactrian camels, the economy boomed and Buddhism flourished. More than anything, though, Dunhuang has become synonymous with one of the world’s most spectacular cultural sites — the Mogao Buddhist cave temples.</p><p>This historical source can be traced back to the fourth century AD. From then to the 14th century, Dunhuang evolved into a crossroads of humanity thanks to its strategic geographic position. The Mogao caves, located 16 miles (25 km) outside of the oasis of Dunhuang, became a visual repository of the religious, artistic, economic, political and social life of the region, illustrated in wall paintings, portrayed in sculptures, and reflected in objects and documents found inside the caves.</p><p>After visiting some Dunhuang exhibitions, I give some photos of the exhibits for everyone to have a glimpse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wr6BuuqR1T2BKGZrik1SuA.jpeg" /><figcaption>photo: a servant of the wall painting in the Thousand Buddha Caves</figcaption></figure><p>Based on the famous painted statues and murals in Dunhuang Grottoes, it breaks the form of static exhibitions of sculptures and murals, and innovatively interprets classic statues such as Maitreya with crossed feet in Beiliang, reclining Buddha in Tang Dynasty, and Buddha sitting in a seated way with light and shadow. The dignity and majesty of the main Buddha statue, the humility and obedience of the disciples, the graceful and graceful Bodhisattva, and the brave and majestic king of heaven fully reflect the inner characters of different characters and demonstrate the superb sculpture level of the prosperous Tang Dynasty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ORIyVYEL7oiuk0eqbaAW0Q.jpeg" /><figcaption>the exhibit of the Thousand Buddha Caves</figcaption></figure><p>The other most famous story from Dunhuang is the Deer of Nine Colors. It tells a tale: In ancient times, a Persian merchant gets lost in a great windstorm. Suddenly, though, a spiritual deer of nine colors appears to guide the man. Later, the deer rescues a man drowning in a lake. In exchange, the man promises not to reveal the deer’s whereabouts. The man reaches an imperial palace. The king insists on hunting down the spiritual deer down to make clothes out of the deer skin. The man gives in to his greed and leads an army of warriors to the spot. He falls into the river again, hoping the deer will show up to rescue him. This time, all the warriors’ arrows turn into dust and the man is drowned.</p><p>In the exhibition, the tale is shown with modern lighting technology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h50R3OS2uOIjltsbOoENKQ.jpeg" /><figcaption>the light show of the deer</figcaption></figure><p>The Deer was a past life incarnation of Shakyamuni Buddha, which deepens the Buddhist ethos in Dunhuang.</p><p>However, the exhibition is displayed in digital form, which is still very different from the real thing. If you want to truly experience Dunhuang art, you still have to go there in person.</p><p>So, plan your journey and go ahead✈️.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5BOhzsYoPBstTyaR6zqLA.jpeg" /><figcaption>Dunhuang Door</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc9014e3e78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plain-plan/dunhuang-a-brief-art-guide-bdc9014e3e78">Dunhuang — a brief Art  Guide</a> was originally published in <a href="https://medium.com/plain-plan">Plain Plan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foreword about Plain Plan]]></title>
            <link>https://medium.com/plain-plan/foreword-about-plain-plan-1ff81001b5b5?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ff81001b5b5</guid>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[publication]]></category>
            <category><![CDATA[publications-on-medium]]></category>
            <category><![CDATA[planning]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 16:33:27 GMT</pubDate>
            <atom:updated>2023-07-04T16:33:27.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*3MnDVHLVgGBW-oLxeX5oMA.jpeg" /><figcaption>image by author</figcaption></figure><p>For a long time, I’ve tried to find my own path in life. When my grandfather was about to die of illness, he summoned me to follow my father’s plan for me. My father is a factory owner, and he witnessed the rise of an industry, and now the industry he has been working on for more than 30 years is gradually falling, and its former glory is no longer. Therefore, the factory where my father has poured his heart and soul into has also gone from bad to worse since then. He asked me to study hard and choose an easier path for earning a life than by managing a factory. In China, everything should be done step by step, doing the right thing at the right time is much better than breaking the usual, and living an ordinary but stable life is much more meaningful than a life where one has ricked all over the world or explored the cosmos.</p><p>Not only these old-days industries the last generations work on are declining, but new star industries such as autonomous driving are facing the crisis of entering a cold winter. The company I work for is also in financial trouble. So I have to think over my future plan. A lot of confusion appeared in front of me, where I should go and what else I can do.</p><p>I used to hate planning as I was a student whether I am in China or Germany. As a student, I had much enough time to kill, more specifically to say, a student shall enjoy life. In Western countries, enjoying one’s life is something essential in society. On the contrary, working hard may be something engraved in the bones of Chinese people, and that’s been common sense in China for many thousand years.</p><p>It’s hard when someone in China doesn&#39;t know how to plan his tomorrow since young. So I have to plan many things after I started my work in China, which includes life, work, even relationships, and family. It may sound sad.</p><p>put it another way, or search the recommendations from Google, “what’s the benefits of planning”, we can get comforted on the other hand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDyRdA_mpFG3y0Oljmu9LQ.png" /><figcaption>screenshot in Google</figcaption></figure><p>As listed above, many known popular effects…</p><p>So, I think it’s somehow meaningful to create this publication, named Plain Plan, for short P Plan. I think a good plan must sound plain and simple, easy to explain and to be understood, but also practicable. When the plan is listed in detail, the sponsor can follow it and implement it, but anyone else who knows it can also complete the plan. I believe, what benefits of planning there will be is much more than Google knows.</p><p>Thus, here we would like to collect all these plain plans from all over the world and different dimensions, including topics from life, job, and travel.</p><p>Last but not least, I appeal to everyone to support our publication and share their plans and stories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ff81001b5b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plain-plan/foreword-about-plain-plan-1ff81001b5b5">Foreword about Plain Plan</a> was originally published in <a href="https://medium.com/plain-plan">Plain Plan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Python to Convert Simple Excel Data to Charts]]></title>
            <link>https://python.plainenglish.io/using-python-to-convert-simple-excel-data-to-charts-cd2192d74ab?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd2192d74ab</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Wed, 22 Sep 2021 02:52:15 GMT</pubDate>
            <atom:updated>2021-09-22T12:43:55.137Z</atom:updated>
            <content:encoded><![CDATA[<p>A good chart is much better than a thousand words, while a good Python chart is made with less than a hundred lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-pfWgWB-ohU5KRnwyqrtxA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@habibdadkhah?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Habib Dadkhah</a> on <a href="https://unsplash.com/s/photos/microsoft-excel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In the last several months, I have moved from Germany back to China. Finally, I started my work in China, thus, there&#39;s little free time for me to post something new here.🙃</p><p>Let’s turn back to our today’s topic. An Excel with two tables is given, the first sheet “working_hours” represents how many hours each worker group monthly works and the second “finished_pieces” tells how many pieces of products are finished by each group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ud8csf1MXS44W02RD_u8Cw.png" /><figcaption>image by author (screenshot from Excel)</figcaption></figure><p>how can we turn it into meaningful charts (maybe beautiful maybe ugly👽), at least the results should convert the main information intuitively?</p><p>Since Python has been a charmer for data scientists for a while now, there are more and more people flourishing their Python skills. It’s popular and convenient to solve data analysis or data visualization tasks with Python. To do these tasks, there is a list of Python libraries we have to know about.</p><h3>1. Python libraries</h3><blockquote><a href="https://pandas.pydata.org/docs/">pandas</a> is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.</blockquote><p>For this story, pandas provide us with functions to read, prepare and preprocess raw data from excel/csv. The data will be saved in form of Dataframe (df), which looks like two-dimensional, size-mutable, potentially heterogeneous tabular data.</p><p>The second step for the story is visualization, which will be done with matplotlib, a library for Python visualization.</p><blockquote><a href="https://matplotlib.org/">Matplotlib</a> is a comprehensive library for creating static, animated, and interactive visualizations in Python.</blockquote><h3>2. About Coding IDE</h3><p>What we want is to make easy things easy and hard things possible. So don’t let coding IDE be a stumbling block on your path to success. If you have spent hours installing an IDE and configuring the IDE environment, you have to find another way. Usually, we use PyCharm, VS Code, Spyder for coding Python. They are good enough, but not always necessary. Sometimes, .txt editor meets all your demands, such as vi (vim), nano, even word 😋.</p><p>So I just installed Python 3.9 on my Mac and setting a venv with both aforementioned libraries, pandas and matplotlib.</p><p>The code is relatively short and easy. So I directly pasted it below:</p><p><em>Attention: before starting code, I saved the two excel sheets as .csv respectively.</em></p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br>import os<br>path=&#39;/Users/yefengxia/Desktop&#39;<br>os.chdir(path)<br>df1=pd.read_csv(&#39;working_hours.csv&#39;,index_col=0)<br>df2=pd.read_csv(&#39;finished_pieces.csv&#39;,index_col=0)<br>df1=df1.fillna(0)<br>df2=df2.fillna(0)<br>df1[&#39;sum&#39;]=df1.sum(axis=1)<br>df2[&#39;sum&#39;]=df2.sum(axis=1)<br>df1.loc[&quot;Total&quot;] = df1.sum(numeric_only=True,axis=0)<br>df2.loc[&quot;Total&quot;] = df2.sum(numeric_only=True,axis=0)<br>cm = plt.cm.get_cmap(&#39;Accent&#39;) #Pastel<br>C=[cm(x) for x in range(8)]<br>fig,ax = plt.subplots(4,figsize=(10,6),sharey=True)<br>axs=[&#39;ax0&#39;,&#39;ax1&#39;,&#39;ax2&#39;,&#39;ax3&#39;]<br>title_=[&#39;group1&#39;,&#39;group2&#39;,&#39;group3&#39;,&#39;total&#39;]<br>for i in range(4):<br> ax[i].bar(df1.columns[0:-1],df1.iloc[i,0:-1],width=0.8,color=C)<br> ax[i].set_xlabel(&#39;month&#39;,fontsize=8)<br> ax[i].set_ylabel(&#39;hours&#39;,fontsize=8)       ax[i].set_title(title_[i],x=0.05,y=.75,fontsize=10,fontweight=&#39;bold&#39;)<br> cmd = &#39;%s=ax[i].twinx()&#39;%axs[i]<br> exec(cmd)<br>  cmd1=&quot;%s.plot(df2.iloc[i,0:-1],color=&#39;red&#39;,alpha=0.3,marker=&#39;*&#39;)&quot;%axs[i]<br> cmd2=&quot;%s.set_ylim(0,12)&quot;%axs[i]<br> cmd3=&quot;%s.set_ylabel(&#39;amount&#39;,fontsize=8)&quot;%axs[i]<br> exec(cmd1)<br> exec(cmd2)<br> exec(cmd3)<br> for index,v in enumerate(df1.iloc[i,0:-1]):<br>   ax[i].text(index-.05,v+20, str(round(v)),color=C[index],fontweight=&#39;bold&#39;,fontsize=7)<br>fig.tight_layout()<br>plt.show()</pre><p>On my laptop, I just wrote the code with <a href="https://www.nano-editor.org/docs.php">nano</a>, whose interface clean and simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QI4k9jR5aA1dDPO4FF6xuA.png" /><figcaption>image by author (nano interface)</figcaption></figure><h3>3. explain the chart design</h3><p>After the code above executed, we get the plot📊.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7ipkIUC_00pQyKP29ApAg.png" /><figcaption>image by author (excel data plot)</figcaption></figure><p>Being compared with tabular data from excel, this chart is much more intuitive, delivering information more directly.</p><p>We can dig into the plot and find out the used skills.</p><p>The first part is concerned about pandas, we have to do a little data cleaning since a part of Excel data is lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uaYDByFxx2ZrdfA_HbrxoQ.png" /><figcaption>The cells filled with yellow lack of numbers (NaN)</figcaption></figure><p>To fill the blanks, we can take advantage of the pandas built-in function <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html">fillna()</a>, which fills NA/NaN values using the specified method.</p><blockquote>df=df.fillna(0)</blockquote><p>And then, we add sum row (column) after the last row (column).</p><blockquote>df[&#39;sum&#39;]=df.sum(axis=1) # add new column<br>df.loc[&quot;Total&quot;] = df.sum(numeric_only=True,axis=0) # add new row</blockquote><p>If we print the dataframe in the terminal, there is now one more row and column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFMNT1k50LWvNb7t-CxCow.png" /><figcaption>print(df)</figcaption></figure><p>However, there are two sheets with different content. If we want to integrate their information into one chart, we need to add a y-axis label to secondary y-axis in matplotlib.</p><p>According to <a href="https://stackoverflow.com/questions/14762181/adding-a-y-axis-label-to-secondary-y-axis-in-matplotlib/14762601">stack overflow</a>, there are two ways:</p><ol><li>using an attribute in plot, secondary_y=True</li><li>interact with the axes object directly by <em>twinx()</em></li></ol><p>In our code, we used the second method to define new axes object with twinx().</p><p>Then, we can show the two sheets’ information in one figure with left-yaxis and right-yaxis. After that, we still need to plot 4 rows’ data in each table. To demonstrate it clear, here we take 4 subplots to show the data of the 1,2,3 group and the sum of them. Therewith, using a for-loop or while-loop is meaningful. It’s not easy to define different object variable names while in a loop. A good solution is to define variable names with loop variable <em>i </em>and execute it with function <em>exec().</em><strong>exec()</strong> function is used for the dynamic execution of Python program which can either be a string or object code.</p><pre>cmd = &#39;%s=ax[i].twinx()&#39;%axs[i] #make twin axis based on x<br>exec(cmd) # execute the code saved in cmd</pre><p>Then, the code repeats the process to create axes and after 4 iterations there are 4 subplots, each with secondary y-axis.</p><h3>4. analysis the chart</h3><p>Before we go ahead to discuss the plotted chart, there is one thing we should know in advance. In the row, “group two” is set up newly in April. The workers in “group two” need training and help from “group one”. The main work from group one and two is the same, both are responsible for mechanical assembly work, while group three contributes to electric welding. Therefore, the work intensity of group 3 has the same tendency as the total work intensity. Because there is no other group that takes the same work as group 3. And group one and two have the same work content and can exchange shifts among their workers. Besides, group one is responsible for training working-skill of group two. Therewith, group one hasn’t increased its workload since May and group two can’t provide many working hours with lack of skill and experience.</p><p>That’s all that we want to share in today’s story. Thanks 🙏</p><p>May you succeed!🚀🚀🚀</p><h3>Other relative stories</h3><ul><li><a href="https://towardsdatascience.com/how-to-draw-a-bar-graph-for-your-scientific-paper-with-python-a6c2a5e6bcd7">How to draw a bar graph for your scientific paper with python</a></li><li><a href="https://towardsdatascience.com/creative-report-designed-only-with-matplotlib-without-office-software-9d8b5af4f9c2">Creative report designed only with Matplotlib, without office software</a></li><li><a href="https://towardsdatascience.com/donut-plot-for-data-analysis-5aacac591741">Donut plot for data analysis</a></li></ul><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd2192d74ab" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/using-python-to-convert-simple-excel-data-to-charts-cd2192d74ab">Use Python to Convert Simple Excel Data to Charts</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plan your own Computer Vision journey, may you succeed]]></title>
            <link>https://ai.plainenglish.io/plan-your-own-computer-vision-journey-may-you-succeed-22fdfc5c52f5?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/22fdfc5c52f5</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 09:42:10 GMT</pubDate>
            <atom:updated>2021-01-27T13:01:57.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>Plan your own Computer Vision journey <strong>from scratch</strong>, may you succeed</h3><p>In this article, I generated an image dataset with Matplotlib, submitted it to Kaggle and trained a vanilla CNN model on Google Colab. My individual Computer Vision trip bundles together data-generating, preprocessing, modeling and evaluation steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eOiNbf4g18NeQ67Fg_XoDA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mattpopovich?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matt Popovich</a> on <a href="https://unsplash.com/s/photos/star-wars?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>My own journey</h3><p>I started my Computer Vision journey in a german Industrie, where one of my tasks is to take pictures for building an image dataset of machined parts’ surface. Later we built a model to classify and Individuate anomalies with Convolutional Neural Networks. It sounds cool, however, the work for collecting images using an industrial camera is not easy, in contrast always time-consuming.</p><p>Of course, there are plenty of image datasets available, such as <a href="http://host.robots.ox.ac.uk/pascal/VOC/voc2012/"><strong>VOC 2012</strong></a>, <a href="https://cocodataset.org/#home"><strong>COCO dataset</strong></a>. From websites, e.g. Kaggle, the world’s largest data science community with powerful tools and resources, you can also search for what you want. But for your individual task, there is not always a free, huge dataset of high quality to use for deep learning applications. Web scraping can provide you with a great amount of data, nevertheless, Quality is also difficult to guarantee.</p><p>So I decided to find my own way. Why not build my image datasets with Python!</p><h3>Task</h3><p>If my words have inspired you so far, please follow my text to start an imagination trip of Computer Vision.</p><p>In school, we have all hated mathematical functions more or less. Sorry for my aggressive words if you have fallen in love with them. Our teachers must have taught us how to identify functions using graphs. It doesn’t matter how good you still can since I want to build a model to tell what type of function it is based on its graph.</p><p>I have just come up with my wild idea. So it’s hard to find a proper dataset that meets my command. To simplify our task and make it more achievable, I have to select some function types out of interest. Because there are infinite function types in the math world. So I listed 5 common functions:</p><ul><li><em>linear function: y=mx+b</em></li><li><em>square function: y=ax²+bx+c</em></li><li><em>cube function: y=ax³+bx²+cx+d</em></li><li><em>square root function: y=ax^(1/2)+b</em></li><li><em>reciprocal function: y=m/x+b</em></li></ul><p>They have polynomials in one variable (x) on the one side of the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*CIWvdSAwgAzsBU0LaIKozQ.png" /></figure><h3>Manufacture image data</h3><p>I imported the Package Matplotlib in Python, repeated drawing graphs of these 5 kinds of functions with random parameter and random axes styles, such as line style, figure title, legend, figure grid, label… I don’t want to add an unnecessary variable color so the generated images are all monochrome.</p><p>In the end, I got 2050 pieces of graph for each kind of above-listed functions. Why 2050, no more no less? That is just a sense, the quantity of the dataset depends on your judgment and decision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*ge3hr_hXJGX8MDdxLXjqKQ.png" /><figcaption>Image by Author: function graph example for each kind of functions</figcaption></figure><p>Additionally, I set pyplot figure with size (5,5) and dpi=50. Therewith, among the image dataset, the image size is the same, namely 250x250.</p><h3>Submit dataset on Kaggle</h3><p>Next step, we shared our own dataset on Kaggle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhWMUDLYSsPwXwICYgBqNA.png" /><figcaption>Image by Author: screenshot of Kaggle after clicking “+New Dataset”</figcaption></figure><p>Drag a ZIP or folder of the dataset into the center field of the Kaggle page. It makes the dataset more accessible and looks clean when we upload a CSV file meanwhile which contains image names with different categories (labels).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*pwR6XcSwHnKVMdtT_J_XPg.png" /><figcaption>Image by Author</figcaption></figure><p>You can set your dataset either private or public. Adding descriptions for your dataset is helpful for others so that they can understand the content and task at the first glance.</p><h3>Code on Google Colab</h3><blockquote>Colab is a Google research project created to help disseminate machine learning education and research.</blockquote><p>Similar to the Jupyter notebook environment, but it requires no setup to use and it can run entirely in the cloud or bond with localhost.</p><p>The biggest advantage: In most cases, Colab is free and provides free GPU.</p><p>Here is my workflow on Colab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*moMw4pX4ZPp_rU5MRbg3KA.png" /><figcaption>image by Author: screenshot of Colab page.</figcaption></figure><p>To use datasets on Kaggle directly, we need to install Kaggle API on Colab. Otherwise, we should download the required dataset from Kaggle, save it on the local host (PC), and upload data to Colab, connect Colab with Drive. How much time can be wasted during the redundant procedure?</p><p>Using Kaggle API, we can download the dataset directly on Colab/Driver, of course, we need to mount Drive on Colab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*LZmv53OV_sU7shEXBGRw1g.png" /><figcaption>image by Author: code for mounting gdrive on Colab</figcaption></figure><h3>Vanilla CNN</h3><p>Here “Vanilla” has nothing to do with taste. It’s a common euphemism for “regular” or “without any fancy stuff.” Below is a typical structure for a vanilla CNN, which consists of <strong><em>convolutional layers, pooling layers, a flattening layer and dense layers.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*INozjSyU3hs2gIoX4gpDEg.png" /><figcaption>Image by <a href="https://www.researchgate.net/profile/Jose_Benitez_Andrades">Jose Alberto Benítez Andrades</a>: a vanilla Convolutional Neural Network (CNN) representation.</figcaption></figure><p>If you just google the keyword, there are many useful resources online which work as a simple guide to explain a vanilla CNN in practice. Therewith, I won&#39;t explain much more about CNN.</p><p>Before I build my own vanilla CNN classifier to identify function graphs, I need to load data from images with the following code. There are 2050x5= 10250 images including 5 classes (labels: l, s, c, m, r). I divided them into 3 sets, 7000 images in the train set, 1500 images in the validation set and the rest 1750 images in the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNbwRtob-drmFzE6fO77KQ.png" /><figcaption>image by Author: 10 graphs from the train set, the title represents the label of graph</figcaption></figure><pre>from tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img,img_to_array, array_to_img</pre><pre>train_files = glob.glob(&#39;training-data/*&#39;)<br>train_imgs = [img_to_array(load_img(img, color_mode=&#39;grayscale&#39;,target_size=image_size)) <strong>for</strong> img <strong>in</strong> train_files]<br>validation_files = glob.glob(&#39;validation-data/*&#39;)<br>validation_imgs = [img_to_array(load_img(img, color_mode=&#39;grayscale&#39;,target_size=image_size)) <strong>for</strong> img <strong>in</strong> validation_files]<br>train_imgs = np.array(train_imgs)<br>validation_imgs = np.array(validation_imgs)</pre><p>Then, I can start my main work to build a neural network. I’m used to building a network with TensorFlow.Keras.layers, which saves me a lot of time from writing my own model class than using TensorFlow directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4GYK8HoQqmb5VLLEd2PPw.png" /><figcaption>Image by Author: model graph</figcaption></figure><p>Based on the convenient API, I created a vanilla CNN model for image classification. The last dense layer is the output layer which consists of 5 nodes, since we have 5 different function classes.</p><p>After 3 epochs the training loss and validation loss don’t decrease obviously (metric: Categorical Crossentropy for the multiclass problem). Therewith I can stop the training and save the h5 model file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*rMkptPfmYxQP6bkP7FHCgA.png" /><figcaption>image by Author: training- and validation history plot</figcaption></figure><p>So far, The model is finished! Let’s test it on the test set.</p><h3>Evaluation</h3><p>The predictions on the test set can be evaluated by Accuracy, Precision, Recall, F1 Score. These are common matrics for classification evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJ9yawFccSCJzq-C-GYY-Q.png" /><figcaption>image by Author: classification report</figcaption></figure><p>To better visualize the evaluation results, I used a normalized confusion matrix and plotted it with a heatmap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBjcMzVN8ivKmB0Te4eyQQ.png" /><figcaption>image by Author: confusion matrix heatmap</figcaption></figure><p>All the metrics suggest that the trained model works pretty well on the test set. With the test acc more than 99%, the trained CNN model performs well.</p><p>Below is the whole code for this trip. May you have fun.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/713f814b6b42f4ee6a50129b298cb7aa/href">https://medium.com/media/713f814b6b42f4ee6a50129b298cb7aa/href</a></iframe><h3>Summary</h3><p>In this article, I didn’t focus on many details of CNN structure. Of course, you can change the CNN structure and tune hyperparameters to improve the model (which you can refer to in my previous story). The dataset of function graphs generated by me has completed a self-cycle. It’s an end-to-end Computer Vision trip with image data generating, preprocessing, modeling, and evaluation. That means I designed a dataset and analyzed it on my own, just like I asked a question and answered it myself. It’s not a time-wasting, since I have 100% control over the dataset. The workflow introduced in this article is especially efficient for an individual to complete his task and control modeling. I review the workflow here with keywords:</p><ol><li>dataset generation.</li><li>dataset submission.</li><li>dataset analysis with machine learning model (deep learning model).</li><li>evaluation.</li></ol><p>On the one hand, it can realize the basic CV (NLP…) task. On the other hand, it’s suitable to test all kinds of models with different parameters on the dataset. It’s easy to compare all kinds of Machine learning (Deep learning) models.</p><h3>References</h3><ul><li><a href="https://github.com/Kopfgeldjaeger/Medium_blogs_code/tree/master/6_DIY_CV_trip">Kopfgeldjaeger/Medium_blogs_code</a></li><li><a href="https://www.kaggle.com/kopfgeldjaeger/function-graphs-polynomial">Function_Graphs (Polynomial)</a></li><li><a href="https://www.tensorflow.org/guide/keras/sequential_model">The Sequential model | TensorFlow Core</a></li></ul><p><a href="https://ieeexplore.ieee.org/abstract/document/8451339?casa_token=U7zm2MZGWXoAAAAA:bo2QwOH7kQ_qgXnDWlC8erSv90lkuLia5J8xNH9Xko3xk1g2cmfYPWxOGEugYj0spjWJybVE">I. Freeman, L. Roese-Koerner and A. Kummert, “Effnet: An Efficient Structure for Convolutional Neural Networks,” 2018 25th IEEE International Conference on Image Processing (ICIP), Athens, 2018, pp. 6–10, doi: 10.1109/ICIP.2018.8451339 .</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22fdfc5c52f5" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/plan-your-own-computer-vision-journey-may-you-succeed-22fdfc5c52f5">Plan your own Computer Vision journey, may you succeed</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Analog Clock using Python]]></title>
            <link>https://python.plainenglish.io/building-an-analog-clock-using-python-518922d57784?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/518922d57784</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[matplotlib]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Sat, 23 Jan 2021 19:09:53 GMT</pubDate>
            <atom:updated>2021-01-25T08:27:52.671Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create a simple analog clock with Matplotlib package</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0Ca4BB8o_8riXrHv_7z8Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@silotis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Simon</a> on <a href="https://unsplash.com/s/photos/analog-clock?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article, I will show you the process to build and design your analog clock using python package matplotlib.</p><blockquote><strong>Matplotlib</strong> is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+. — <a href="https://en.wikipedia.org/wiki/Matplotlib">Wikipedia</a></blockquote><p>Online there are already many text and video tutorials to tell us how to create an analog or digital clock, typically with Qt, Tkinter which are usually used for GUI building. Another most famous package turtle is frequently introduced in python crash course, which is a pre-installed Python library that enables users to create pictures and shapes by providing them with a virtual canvas. We can also use turtle to design our clock, but not today, not here🙂.</p><p>However, matplotlib as one of the essential data science packages plays an important role to produce cross-platform charts and figures. Personally, I particularly prefer this package to complete my daily study and work. With Matplotlib, I can accomplish tasks effectively. At the end of this article, I will list my previous stories related to Matplotlib.</p><h3>Coordinate system</h3><p>You can be a great programmer even if you were bad at math in school. But if you know a little math you can do better. And it can surprise you if you have learned a great lot of math.</p><p>for our task, we need basic knowledge about coordinate systems.</p><blockquote>In geometry, a coordinate system is a system that uses one or more numbers, or coordinates, to uniquely determine the position of the points or other geometric elements on a manifold such as Euclidean space. — <a href="https://en.wikipedia.org/wiki/Coordinate_system">Wikipedia</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-92oxIMOBlbEvOdI1rpgg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@joshuas?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Joshua Sukoff</a> on <a href="https://unsplash.com/s/photos/spiral?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There are 4 kinds of commonly used coordinate systems in math world: Cartesian coordinate system, Polar coordinate system, Cylindrical and spherical coordinate systems, Homogeneous coordinate system. In our daily life we have used the first one for the most cases, Cartesian coordinate system, where a point is taken to be the signed distances to the lines. The distances are represented by x, y (including z for 3D).</p><blockquote>For the plane is the <a href="https://en.wikipedia.org/wiki/Polar_coordinate_system"><em>polar coordinate system</em></a><em> </em>another frequently used coordinate system. A point is chosen as the <em>pole</em> and a ray from this point is taken as the <em>polar axis</em>. For a given angle θ, there is a single line through the pole whose angle with the polar axis is θ (measured counterclockwise from the axis to the line).</blockquote><p>A clock, in general, has 12 numbers written on it, from 1 to 12, an hour hand, and a minute hand and somethings plus a second hand. Clock angle problems relate to two different measurements: angles and time. The hour-hand of a normal analog clock turns 360° in 12 hours (720 minutes) or 0.5° per minute. The minute-hand rotates through 360° in 1 hour or 6° per minute. The second-hand turns 360° in 1 minute (60 seconds) or 6° per second. They all run around the center point in the clock face. Therewith, they can be imaged in the same polar coordinate. Differently, they run clockwise, which should be taken into consideration in code.</p><p>we mainly take advantage of the polar coordinate system for our analog clock mechanism with matplotlib. I wrote this section which is the essential math thought for the below code.</p><h3>Let’s start with Code in Python</h3><p>Firstly import the packages. From numpy, we just adopted the number Pi, which represents the angle of clock hands. Based on Radians to Degrees conversion, 1 Pi is 180°. As promised, we count on matplotlib. FuncAnimation is the key to make our clock run, with which we can make an animation by repeatedly calling an update function.</p><p>When using Matplotlib’s polar plot, the default zero position for the theta axis is on the right with the angle increasing counter-clockwise. So we need to change the default settings.</p><p>Within the update function, we clear the last plot with “plt.cla()” so that there is nothing left in the figure. we define the axes setting every time, that xticks from 1 to 12 clockwise and 1 at the top of a clock face. And theta offset is added so that the zero position for the axis is now on the top of the clock face. Next, we read time from “datetime.datetime.now()” and transfer time into degree and pass degree into respective variables. Hour-hand, minute-hand and second-hand can be plotted whose angle is dependent on the current time. Lastly, return axes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d89dd7a2b6800f07f43f090d65e04fa/href">https://medium.com/media/7d89dd7a2b6800f07f43f090d65e04fa/href</a></iframe><p>FuncAnimation repeats the plot of a clock with current time and refreshs it every 100 milliseconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*ypeOsXQf0sh8r05o_0RT3w.gif" /><figcaption>image by Author (left: the online analog clock in my region. right: our built analog clock with Matplotlib)</figcaption></figure><p>The above .gif shows that our analog clock (left) works as well as other clocks (right).</p><p>So, we made it!</p><h3>Outlook</h3><p>What’s more, we can also decorate it more beautifully, such as the color of the clock face and background, shape and color of hands, etc.</p><p>By using annotation function “plt.annotate” or “plt.text”, we can also add a line of date under our analog clock. But the clock is not a pure analog clock anymore, so I didn’t add it. If you are interested, you can download code from my <a href="https://github.com/Kopfgeldjaeger/Clock_project">Repository on GitHub</a> and modify it to make your own analog clock.</p><h3>related stories to Matplotlib</h3><ul><li><a href="https://towardsdatascience.com/creative-report-designed-only-with-matplotlib-without-office-software-9d8b5af4f9c2">Creative report designed only with Matplotlib, without office software</a></li><li><a href="https://towardsdatascience.com/donut-plot-for-data-analysis-5aacac591741">Donut plot for data analysis</a></li><li><a href="https://towardsdatascience.com/how-to-draw-a-bar-graph-for-your-scientific-paper-with-python-a6c2a5e6bcd7">How to draw a bar graph for your scientific paper with python</a></li></ul><h3>References</h3><p><a href="https://matplotlib.org/3.1.1/api/animation_api.html">https://matplotlib.org/3.1.1/api/animation_api.html</a></p><p><a href="https://docs.python.org/3/library/datetime.html">datetime - Basic date and time types</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=518922d57784" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/building-an-analog-clock-using-python-518922d57784">Building an Analog Clock using Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Naive Bayes fails to tell if you have Covid-19]]></title>
            <link>https://medium.datadriveninvestor.com/why-naive-bayes-fails-to-tell-if-you-have-covid-19-54aae712a590?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/54aae712a590</guid>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 13:25:50 GMT</pubDate>
            <atom:updated>2021-01-18T09:54:36.979Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we focus on a naive Bayes classifier to check if somebody has covid-19 or not, and how severe is his infection, based on his symptoms. As the title revealed, the test prediction accuracy is not satisfying which fails to determine the severity of the infection with this method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJAInEYFb6HjI9gAA9snUA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Annie Spratt</a> on <a href="https://unsplash.com/s/photos/covid-19-test?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>1. Kaggle dataset</h3><blockquote>These data will help to identify whether any person is having a coronavirus disease or not based on some pre-defined standard symptoms. These symptoms are based on guidelines given by the World Health Organization (WHO)<a href="https://www.who.int/">who.int</a> and the Ministry of Health and Family Welfare, India.</blockquote><p><a href="https://www.kaggle.com/iamhungundji/covid19-symptoms-checker">COVID-19 Symptoms Checker</a></p><p>The dataset contains seven major variables, the descriptions of each variable are as follows:</p><ol><li>Symptoms: According to WHO, 5 are major symptoms of COVID-19, Fever, Tiredness, Difficulty in breathing, Dry cough, and sore throat.</li><li>Experience any other symptoms: Pains, Nasal Congestion, Runny Nose, Diarrhea, and Other.</li><li>Gender: There are 3 genders (Male, Female, Transgender)</li><li>Classification of the age group for each person, based on WHO Age Group Standard</li><li>Has the person contacted some other COVID-19 patient</li><li>The level of severity, None, Mild, Moderate, Severe</li><li>Country: List of countries person visited (including China, France, Germany, Iran, Italy, Other, Other-EUR, Republic of Korean, Spain and UAE.</li></ol><h3>2. data preprocessing</h3><p>There are two CSV files uploaded in this Kaggle data repository. To save time, I have just picked the cleaned data and skipped the step — data cleaning.</p><p>Obviously, there are categorical features in the given data set, e.g. country. One simple way to deal with them is by assigning a number to them, code looks like the following:</p><pre># df is the data frame read the csv file.<br>country_id = {&quot;Country&quot;:     {&quot;China&quot;: 0, &quot;UAE&quot;: 1, &#39;Italy&#39;:2,&#39;Spain&#39;:3,&#39;Iran&#39;:4,&#39;Republic of Korean&#39;:5,<br>                              &#39;France&#39;:6,&#39;Germany&#39;:7,&#39;Other-EUR&#39;:8,&#39;Other&#39;:9}}<br>df = df.replace(country_id)</pre><p>Some features, such as age, gender, severity are described by a binary vector of the size of the number of distinct elements. There is no problem but we just want all features in the same format. Therewith, we need to handle them for example, with the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*qJCtSL2ppUEFyf08QZ6xng.png" /></figure><pre>df[&#39;Age&#39;] = df[&#39;Age_0-9&#39;]*0+df[&#39;Age_10-19&#39;]*1+df[&#39;Age_20-24&#39;]*2+df[&#39;Age_25-59&#39;]*3+df[&#39;Age_60+&#39;]*4</pre><p>The idea is very easy to label the age feature with <strong>Ordinal Variables</strong>, which will be also used in all features. We can call this process Ordinal Encoding, useful for categorical variables that have a natural rank ordering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*3tULr8vFNRE1jlie9Fj08Q.png" /><figcaption>Image by Author: display of the dataframe, before and after the processes in this section. Comments: the output (Y1, Y2, Y3, Y4) is column 19–22 at the image left. The new output (Y, the only one) is column 15 at the image right.</figcaption></figure><h3>3. Naive Bayes</h3><p>A Naive Bayes classifier is a probabilistic machine learning model that’s used for the classification task. Classification is a two-step process, learning step and prediction step. In the learning step, the model is developed based on given training data. In the prediction step, the model is used to predict the response for given data. The naive Bayes classifier greatly simplify learning by assuming that features are independent given class, that is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*6DrAL45OC8YctbkjrqQYtA.png" /></figure><p>where X=X1, X2, .. , Xn, is a feature vector and Y is a class.</p><p>According to Bayes’ theorem, where A and B are events and P(B) is not zero, the conditional probability can be calculated with the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*TQJfSdJu7BxMyr1PnfWY6Q.png" /></figure><p>This formula contributes to <strong>Bayesian inference</strong>, where<strong> </strong>the probability for a hypothesis can be conducted. In view of antecedents and consequences, if A is the consequence, then B is the potential variable that brings about A. In a classification problem, Y represents class and X is feature. We can find out the prediction of Y is based on the observation of X.</p><p>If X with n dimensions is given and Y belongs to {c1,c2, …, ck}, a set of all possible classes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*QuD9etLPElXIK6sEQN0IfA.png" /></figure><p>since each feature in X vector is independent, therewith</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*2SZPhLWE-8Csz1MhJQZPxg.png" /></figure><p>by combining these two formulas, we get the expression of naive Bayes classifier, which is essential for our programming work later. In our Code, we just used NumPy and Pandas, so that we get a further understanding of this mathematical expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*Z_MiQFb32x6b5jDhkix2Ww.png" /></figure><p>Naive Bayes has proven effective in many practical applications, including text classification, medical diagnosis, and systems performance management.</p><h3>4. Naive Bayes classifier with Numpy and Pandas</h3><p>Firstly, we should split data into train and test sets. Like most people, we divide 80% of the data in the train set and the rest in the test set.</p><pre>np.random.seed(1)<br>train=df.sample(frac=0.8,random_state=1) <br>test=df.drop(train.index)</pre><p>Then we started with calculating the prior probability P(Y=ck).</p><pre>prior = (train.groupby(&#39;Severity&#39;).size()).div(len(train)) <br>print(prior)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*CAjZDu8SsTioEP11LxCGyg.png" /><figcaption>image by Author: index: 0 represents none in severity, in other words, not infected; 1 is mild severity; 2 is moderate severity; 3 is a severe infection. values at the left represent the prior probability of y=0, 1, 2, 3.</figcaption></figure><p>Based on the prior probabilities, we can go on to calculate probabilities of finding each feature given class label.</p><pre>likelihood = {}<br><strong>for</strong> x <strong>in</strong> train.columns[:-1]:<br>  likelihood[x] = (train.groupby([&#39;Severity&#39;,x]).size()).div(len(train)).div(prior)</pre><p>In the dictionary likelihood, we saved the posterior probabilities of the required naive Bayes classifier for our task — covid-19 checker.</p><p>To predict if someone has covid-19 or not, we only need to enter a feature vector of all kinds of symptoms, experiences and personal information. Then the model can tell us whether he has gotten covid-19 and how severe is his infection already. The whole code is written on Colab.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e4360676eab7925e7956268066da320/href">https://medium.com/media/3e4360676eab7925e7956268066da320/href</a></iframe><p>However, the test result of the model is not so good as we thought:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*ScpRRyrTk9WI0I7SSn9P0g.png" /><figcaption>image by Author: prediction in the test set</figcaption></figure><p>By the way, we don&#39;t have to realize Bayes classifier every time only with Pandas or Numpy. We can directly import the proper classifier from Sklearn as follows:</p><pre><strong>from</strong> <strong>sklearn.naive_bayes</strong> <strong>import</strong> GaussianNB,CategoricalNB<br>gnb = CategoricalNB()<br>y_pred = gnb.fit(x_train, y_train).predict(x_test)</pre><p>In this article, we coded with Numpy and Pandas just to let the process a little more transparent and intuitive. If you are not strange with the Bayes classification model, Sklearn is highly recommended, which is more efficient.</p><h3>5. Evaluation</h3><p>So far we have trained a naive Bayes classifier for checking covid-19 infection based on the given dataset from Kaggle. Unluckily, its test set prediction is not better than a shot in the dark which can also reach around 1/4 Acc for 4 targets in Y space.</p><p>So what happened?</p><p>Before we are going to dig into details, one premise we should always keep in our mind is that <strong>features are independent </strong>under the naive Bayes classifier.</p><p>The feature vector for our covid-19 checking consists of major symptoms and other experiences, which are not totally independent of each other. We can imagine that if someone has a fever, that person will also get tired easily. If someone has a stuffy nose now, he may have a runny nose at the next minute. The major symptoms are often accompanied by each other, no matter what kind of infection you have.</p><p>On the other hand, not all of the listed features are significant features for the classification. They may have played a role to show the patient’s situation but not scientific or detailed enough. We know both 37.9°C and 39.9°C is an undoubtful signal of fever. Someone with 37.9°C can hang out meanwhile the other one with 39.9°C must suffer much from fever, which is not clearly interpreted in the given data. A quantitative measure of features can help a lot. In substitution for telling whether has a fever, we could use temperature that will be a more precise description of symptoms. The same for other symptoms, e.g. cough continuously or just once in a while. we need a proper scale to define the features.</p><p>If we could make some corresponding adjustments in these two aspects, the naive Bayes classifier should show its promising performance in checking Covid-19 infection.</p><p>At last, advice has nothing to do with our topic if you feel not well and some symptoms have appeared for days, antibody tests can tell you if you’ve been infected with the virus. Even a most famous doctor can not tell if there’s covid-19 infection only according to your oral description. This is actually the third reason why the trained model not works😅.</p><h3>6. References</h3><p><a href="https://www.cc.gatech.edu/~isbell/reading/papers/Rish.pdf">Rish, Irina. “An empirical study of the naive Bayes classifier.” <em>IJCAI 2001 workshop on empirical methods in artificial intelligence</em>. Vol. 3. №22. 2001.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54aae712a590" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/why-naive-bayes-fails-to-tell-if-you-have-covid-19-54aae712a590">Why Naive Bayes fails to tell if you have Covid-19</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creative report designed only with Matplotlib, without office software]]></title>
            <link>https://medium.com/data-science/creative-report-designed-only-with-matplotlib-without-office-software-9d8b5af4f9c2?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d8b5af4f9c2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[report]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 04:42:50 GMT</pubDate>
            <atom:updated>2021-01-04T13:49:32.859Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, our aim is to create an intuitive report with Matplotlib. <strong>Attention</strong>: during the work, none of the office software will be demanded. What we only use, is Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pv2AJGKWmqbFC9NjAWXuCg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Isaac Smith</a> on <a href="https://unsplash.com/s/photos/annual-report?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>A series of meaningful data plots works usually as ingredients in a report. As spoken, a good chart is better than a speech. If we have obtained these precious ingredients in advance, the last step is how to place them in a proper way.</p><p>Of course, we can use Microsoft Word, Powerpoint, etc. But not necessary. Here I present my recipe with Matplotlib.</p><h3>1. Short introduction of data and charts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*C75FXD5UUd7OnxR7rTNViw.png" /><figcaption>image by Author: excel sheets, the total sales from 2018 to 2020</figcaption></figure><p>Based on the excel file, we have gotten some representative charts (bar plot and donut plot). If you don&#39;t know how to handle this, please check my previous stories. The links are given, please check them one after one if you feel the tasks not easy or new for you.</p><ol><li><a href="https://medium.com/datadriveninvestor/a-short-interview-about-a-chinese-sweatshop-in-the-textile-industry-aefa9c2229ef">Introduction to the factory</a> — the data contributor</li><li><a href="https://towardsdatascience.com/view-a-chinese-factory-from-the-data-aspect-with-python-ad698461f40a">write data into a data frame with Pandas and plot them</a></li><li><a href="https://towardsdatascience.com/data-analytics-helps-warehouse-management-f6a7f44f47af">go deeper with data and explore potential information</a></li><li><a href="https://towardsdatascience.com/donut-plot-for-data-analysis-5aacac591741">how to draw a donut plot</a></li></ol><p>Therewith, we have gathered some charts consisting of one bar plot and nine donut plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*L08fHdHe3B-KD06mATQkpw.png" /><figcaption>image by Author: bar plot of the total sales from 2018 to 2020.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*ynelM0caEk_8iQ1eR98xoQ.png" /><figcaption>image by Author: one of the nine donut plots. <a href="https://github.com/Kopfgeldjaeger/Medium_blogs_code/tree/master/4_donut_plot_and_report/donut%20plots">The donut plots </a>also on Github</figcaption></figure><h3>2. Design layout and basic setting with Matplotlib</h3><pre><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><em># set font</em><br>plt.rcParams[&#39;font.family&#39;] = &#39;sans-serif&#39;<br>plt.rcParams[&#39;font.sans-serif&#39;] = &#39;STIXGeneral&#39;</pre><pre># set A4 paper<br>fig, ax = plt.subplots(figsize=(8.5, 11))  </pre><pre><em># Decorative Lines</em><br>ax.axvline(x=.01, ymin=0, ymax=1, color=&#39;#44A0AD&#39;, alpha=0.3, linewidth=120)<br>plt.axvline(x=.99, color=&#39;#5244AD&#39;, alpha=0.3, linewidth=120)<br>plt.axhline(y=.95, xmin=0.14, xmax=0.86, color=&#39;#446BAD&#39;, linewidth=5,alpha=0.3)<br><br><em># set background color</em><br>ax.set_facecolor(&#39;white&#39;)<br><br><em># remove axes</em><br>plt.axis(&#39;off&#39;)</pre><p>If you enter “plt.show()” now, the figure looks like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*_qNTv5o74AsiaF9v6e1Gzw.png" /><figcaption>Image by Author: report template</figcaption></figure><p>Next, we should add content (title, charts, etc.) to the blank paper.</p><pre>Header = &#39;Annual Report of XXX Factory&#39;<br>Contact = &#39;Reporter:____________ <strong>\n\n</strong>Date:________________ <strong>\n\n</strong>Place:_______________ &#39;<br>page = &#39;Page 1&#39;<br><em># add text</em><br>plt.annotate(Header, (.22,.98), weight=&#39;regular&#39;, fontsize=20, alpha=.6 )<br>plt.annotate(Contact, (.34,.18), weight=&#39;bold&#39;, fontsize=14,alpha=.6)<br>plt.annotate(page, (.48,.02), weight=&#39;medium&#39;, fontsize=10)<br><br><em>#add a vital bar chart</em><br><strong>from</strong> <strong>matplotlib.offsetbox</strong> <strong>import</strong> TextArea, DrawingArea, OffsetImage, AnnotationBbox<br><strong>import</strong> <strong>matplotlib.image</strong> <strong>as</strong> <strong>mpimg</strong><br>first_plot = mpimg.imread(&#39;barplot3.png&#39;)<br>imagebox1 = OffsetImage(first_plot, zoom=0.4)<br>a = AnnotationBbox(imagebox1, (0.48, 0.68),frameon=<strong>False</strong>)<br>ax.add_artist(a)</pre><p>Now, the first page of the report is finished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PG8nkODtr_B2QndJzNokoA.png" /><figcaption>image by Author: the first page of the report</figcaption></figure><p>Similarly, we continue the style on the second page, which should be filled with detailed donut plots for each year.</p><p>To make the content clear, we have to arrange the plots neatly.</p><pre>fig, ax = plt.subplots(figsize=(8.5, 11))<br><br><em># Decorative Lines</em><br>ax.axvline(x=.01, ymin=0, ymax=1, color=&#39;#44A0AD&#39;, alpha=0.3, linewidth=120)<br>plt.axhline(y=.95, xmin=0.14, xmax=0.99, color=&#39;#446BAD&#39;, linewidth=5,alpha=0.3)<br><em># set background color</em><br>ax.set_facecolor(&#39;white&#39;)<br><br><em># remove axes</em><br>plt.axis(&#39;off&#39;)<br>Header = &#39;Annual Report of XXX Factory&#39;<br>page2= &#39;Page 2&#39;<br><em># add text</em><br>plt.annotate(Header, (.22,.98), weight=&#39;regular&#39;, fontsize=20, alpha=.6 )<br>plt.annotate(page2, (.48,.02), weight=&#39;medium&#39;, fontsize=10)<br>first_plot = mpimg.imread(&#39;donutplot1.png&#39;)<br>imagebox1 = OffsetImage(first_plot, zoom=0.25)<br>a1 = AnnotationBbox(imagebox1, (0.29, 0.80),frameon=<strong>False</strong>)<br>ax.add_artist(a1)<br>second_plot = mpimg.imread(&#39;donutplot2.png&#39;)<br>imagebox2 = OffsetImage(second_plot, zoom=0.25)<br>b1 = AnnotationBbox(imagebox2, (0.58, 0.80),frameon=<strong>False</strong>)<br>ax.add_artist(b1)<br>third_plot = mpimg.imread(&#39;donutplot3.png&#39;)<br>imagebox3 = OffsetImage(third_plot, zoom=0.1875)<br>c1 = AnnotationBbox(imagebox3, (0.87, 0.80),frameon=<strong>False</strong>)<br>ax.add_artist(c1)<br><br>fourth_plot = mpimg.imread(&#39;donutplot4.png&#39;)<br>imagebox4 = OffsetImage(fourth_plot, zoom=0.25)<br>a2 = AnnotationBbox(imagebox4, (0.29, 0.50),frameon=<strong>False</strong>)<br>ax.add_artist(a2)<br>fifth_plot = mpimg.imread(&#39;donutplot5.png&#39;)<br>imagebox5 = OffsetImage(fifth_plot, zoom=0.25)<br>b2 = AnnotationBbox(imagebox5, (0.58, 0.50),frameon=<strong>False</strong>)<br>ax.add_artist(b2)<br>sixth_plot = mpimg.imread(&#39;donutplot6.png&#39;)<br>imagebox6 = OffsetImage(sixth_plot, zoom=0.1875)<br>c2 = AnnotationBbox(imagebox6, (0.87, 0.50),frameon=<strong>False</strong>)<br>ax.add_artist(c2)</pre><pre>seventh_plot = mpimg.imread(&#39;donutplot7.png&#39;)<br>imagebox7 = OffsetImage(seventh_plot, zoom=0.25)<br>a3 = AnnotationBbox(imagebox7, (0.29, 0.20),frameon=<strong>False</strong>)<br>ax.add_artist(a3)<br>eighth_plot = mpimg.imread(&#39;donutplot8.png&#39;)<br>imagebox8 = OffsetImage(eighth_plot, zoom=0.25)<br>b3 = AnnotationBbox(imagebox8, (0.58, 0.20),frameon=<strong>False</strong>)<br>ax.add_artist(b3)<br>ninth_plot = mpimg.imread(&#39;donutplot9.png&#39;)<br>imagebox9 = OffsetImage(ninth_plot, zoom=0.1875)<br>c3 = AnnotationBbox(imagebox9, (0.87, 0.20),frameon=<strong>False</strong>)<br>ax.add_artist(c3)<br><br>plt.savefig(&#39;report_2.png&#39;, dpi=300, bbox_inches=&#39;tight&#39;)</pre><p>Therewith, the second page is well decorated with nine donut plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIXFDBuNMyVikD_3LNebtw.png" /><figcaption>image by Author: the second page of the report consisting of detailed data from 2018 to 2020</figcaption></figure><p>Additionally, what we can improve is to draw a conclusion of these plots, which I didn&#39;t have time to write within the report. For example, due to the covid-19 pandemic, the total sales in 2020 are dramatically falling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ooFD7Qfqv2WcgpDik6_5Q.jpeg" /><figcaption>image by Author</figcaption></figure><h3>3. Summary</h3><p>In this short article, the approach to generate a report is explained in detail, which doesn’t need Word or Powerpoint. Our report created by Matplotlib presents relevant information directly obtained by data processing and analysis, which means if you are used to processing data in Python, there is no need to switch apps or platforms.</p><p>The code is submitted in <a href="https://github.com/Kopfgeldjaeger/Medium_blogs_code/tree/master/4_donut_plot_and_report">Github</a>, which you can download and review.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d8b5af4f9c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creative-report-designed-only-with-matplotlib-without-office-software-9d8b5af4f9c2">Creative report designed only with Matplotlib, without office software</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Donut plot for data analysis]]></title>
            <link>https://medium.com/data-science/donut-plot-for-data-analysis-5aacac591741?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aacac591741</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Sun, 03 Jan 2021 20:30:31 GMT</pubDate>
            <atom:updated>2021-01-04T14:17:27.707Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this story, we demonstrate how we draw donut plots from complex excel sheets with python tools.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v20M4kKWT8pUCxQMIT-P9Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@frostroomhead?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rodion Kutsaev</a> on <a href="https://unsplash.com/s/photos/donut-shop?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As usual, our work starts with data, just like some people’s breakfast consists of donuts. There is no relationship between food and data, except that the donut chart has a doughnut-shaped figure.</p><p>Firstly, we have an excel file that records all sales information of an industry department from 2018 to 2020. The department established in 2018 has just experienced covid-19 year in China. Luckily, it has survived and celebrates the starting of the new year 2021.</p><h3>Explanation of original data</h3><p>Now we can look back on what happened to the department in the last three years. The excel composed of 3 sheets, contains the daily sale amount (column E) and the total weight of goods (column F). The receivers of the goods (column C) are actually the companies that pay the money. The product has 3 types (column D) depending on its components, FDY and DTY. generally, There’re 3 combinations of these raw materials, namely FDY-FDY, DTY-DTY, and hybrid FDY-DTY. FAW (column B) determinates the thickness of the product since the finished goods are grey cloth, a basic product in the textile industry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*HlXfUzkhzoIppe1sucjMWQ.png" /><figcaption>image by Author: a screenshot of the excel file</figcaption></figure><h3>Donut plot with Pandas and Matplotlib</h3><pre><strong>import pandas as pd</strong><br>df2018=pd.read_excel(&quot;outbound_with_company.xlsx&quot;,sheet_name=&#39;2018&#39;,header=0)<br>df2019=pd.read_excel(&quot;outbound_with_company.xlsx&quot;,sheet_name=&#39;2019&#39;,header=0)<br>df2020=pd.read_excel(&quot;outbound_with_company.xlsx&quot;,sheet_name=&#39;2020&#39;,header=0)</pre><p>We write each excel sheet into a data frame. The data frame has the same columns as the initial data. We can regroup the data in our minds. If we would like to explore the relationships between orders and costumers, in other words, the numerical proportion between column C and column E (or F), we can regroup the data frame by a groupby operation, which uses the function <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html"><em>pandas.DataFrame.groupby</em></a>.</p><p>Code example:</p><pre>group_2018_2 = df2018.groupby(&#39;company&#39;)<br>print(group_2018_2.size())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*nWxFKe55MC-10rYfPt46Ug.png" /><figcaption>image by Author: code output</figcaption></figure><pre><strong>import</strong> <strong>matplotlib.pyplot as plt</strong><br><strong>from</strong> <strong>matplotlib</strong> <strong>import</strong> <strong>cm</strong><br>fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(aspect=&quot;equal&quot;))<br>cs_customer= cm.get_cmap(&#39;viridis&#39;)(np.linspace(0, 1, 5))<br>component = group_2018_company.index<br>data = group_2018_company[&#39;weight&#39;]<br><br>wedges, texts = ax.pie(data, wedgeprops=dict(width=0.3), startangle=90,colors=cs_customer)<br><br>plt.legend(wedges, component, loc=&quot;center&quot;,fontsize=12)<br><br>ax.set_title(&quot;customers in 2018&quot;,fontdict={&#39;fontsize&#39;: 16, &#39;fontweight&#39;: &#39;bold&#39;})<br><br>fig.tight_layout()<br>plt.savefig(&#39;donutplot2.png&#39;,dpi=100, format=&#39;png&#39;, bbox_inches=&#39;tight&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*ySlnAmJ_svvinXbkGbeBZw.png" /><figcaption>image by Author: output of plt.show(), the donut chart</figcaption></figure><p>From the donut plot, we can clearly see the contribution of each customer to sales. The Customer with ID003 has made the greatest contribution in the year 2018.</p><p>Similarly, we group the data and compute operations on other groups, such as ‘type’, ‘FAW’. Therewith we have obtained three donut plots in 2018.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*1ymXXR6u5FGllRaa2-jwiQ.png" /><figcaption>image by Author</figcaption></figure><p>This excel records 3 years’ sales in the department. That means we can get 9 donut🍩 charts.</p><p>In the next release, we will explain how to build a beautiful annual report by DIY design with Matplotlib.</p><p><a href="https://towardsdatascience.com/creative-report-designed-only-with-matplotlib-without-office-software-9d8b5af4f9c2">Creative report designed only with Matplotlib, without office software</a></p><p>One page of the report looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*MLk772ptaFORFrqTJJnYXA.png" /><figcaption>Image by Author: annual report built with Matplotlib</figcaption></figure><p>All the code and files (png and excel) have been submitted in <a href="https://github.com/Kopfgeldjaeger/Medium_blogs_code/tree/master/4_donut_plot_and_report"><strong>Github</strong></a>.</p><h3>Story review</h3><p>So far, I have written a series of stories based on the same excel file, for which I have posted other related stories, which could help you understand data and data analysis through the real data and case.</p><ul><li><a href="https://medium.com/datadriveninvestor/a-short-interview-about-a-chinese-sweatshop-in-the-textile-industry-aefa9c2229ef">A short interview about a Chinese sweatshop in the textile industry</a></li><li><a href="https://towardsdatascience.com/view-a-chinese-factory-from-the-data-aspect-with-python-ad698461f40a">View a Chinese factory from the data aspect with python</a></li><li><a href="https://towardsdatascience.com/data-analytics-helps-warehouse-management-f6a7f44f47af">Data analytics helps warehouse management</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aacac591741" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/donut-plot-for-data-analysis-5aacac591741">Donut plot for data analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data analytics helps warehouse management]]></title>
            <link>https://medium.com/data-science/data-analytics-helps-warehouse-management-f6a7f44f47af?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6a7f44f47af</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[management]]></category>
            <category><![CDATA[inventory-management]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Thu, 31 Dec 2020 02:01:52 GMT</pubDate>
            <atom:updated>2020-12-31T04:16:37.382Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this story, we can experience how to make use of all the delivery vouchers to monitor the warehouse inventory.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsPRMa6KcxzIgD41btw1TA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@timelabpro?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Timelab Pro</a> on <a href="https://unsplash.com/s/photos/warehouse?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In a supply chain, the warehousing function is very critical to link the material flows between the supplier and customer. Therewith, warehousing is actually part of a material management process concerned with the storage of materials to deliver on time. The warehouse can also be used to store the raw materials, some of the semi-finished goods and parts that are required for manufacturing, and the most important goods — finished goods which will be delivered to customers.</p><p>Last two months I was in a textile factory in China. Through talking with the owner of the factory, I have understood how this factory works to a certain extent. For some industries, the finished goods take up warehouse space enormously, e.g. grey cloth manufacturer.</p><h3>1. Factory introduction</h3><p>The factory 🏭 is in the textile industry on the southeast coast of China, which has more than 30 years of history.</p><p>In recent years, the textile market is volatile. The factory has made some adjustments to cater to the modern market, such as purchasing land, hiring new staff, buying advanced equipment, etc.</p><p>The product of the 30-year-old factory is grey cloth, which is rolled and stacked in the warehouse. The finished cloth rolls are waiting for being delivered by truck. In general, trucks are assigned only by customers. Therewith, the factory can’t send finished goods on its mind and must wait for an appointment from the customer. The stevedores👷🏻 can pick and pack the products until a truck arrives.</p><p>Based on this fact, outbound logistics of the factory is totally dependant on its customers. The manager of the factory can control inbound logistics on his own.</p><p><em>Additionally, if you want to know more details about this factory, you can read the following short story:</em></p><p><a href="https://yefengxia.medium.com/a-short-interview-about-a-chinese-sweatshop-in-the-textile-industry-aefa9c2229ef">A short interview about a Chinese sweatshop in the textile industry</a></p><h3>2. Data availability statements</h3><p>The factory has two manufacturing workshops. In one workshop, there are 22 knitting machines. The other one, which was invested in 2018.02.25, contained 6 knitting machines at the beginning of the year 2018. In the year 2019, a set of new equipment was purchased and put into use. Later in this story, we focus only on the new workshop.<strong> <em>All data and the term factory mentioned in the article only refers to this new workshop</em></strong><em>.</em></p><p>Therewith, the new workshop has 7 sets of production equipment now.</p><p>After getting the factory owner’s support and agreement, I’m allowed to publish this story and share the outbound delivery documents of the new workshop on my <a href="https://github.com/Kopfgeldjaeger/Medium_blogs_code/tree/master/3_pandas_factory">GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ZChL50iZBqLfq0zNtCeM1g.jpeg" /><figcaption>image by Author: an overview of outbound delivery documents of the new workshop in 2018 and 2019. Attention: <strong>Column E tells us how many textile rolls are shipped to the customer in every delivery and Column F how many Kg is the total loaded goods.</strong></figcaption></figure><p>In the last story, I explained how to make this Excel file data visualization with Python. If you are interested in it, you can check it through the link below:</p><p><a href="https://towardsdatascience.com/view-a-chinese-factory-from-the-data-aspect-with-python-ad698461f40a">View a Chinese factory from the data aspect with python</a></p><h3>3. Calculate productivity</h3><p>Through data visualization, we can observe the data more intuitively and clearly. We can plot daily, monthly, or the annual outbound amount by processing available data properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hz3n-43SVYcHeiFui2FeVQ.png" /><figcaption>image by Author: from 2018.02.28 to 2019.12.31, daily shipped goods weight in point plot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZzoIT4zvr-HqUU9qyv4Sg.png" /><figcaption>image by Author: Total annual shipped goods in rolls and total weight in the year 2018 and 2019</figcaption></figure><p>From the bar plot above, we can conclude that the new workshop’s outbound amount has increased after pursuing a new production machine, both on roll number and total cloth weight.</p><p>Since almost all the knitting machines run day and night without stop except factory vacation, which occurs annually once and lasts about one month (not in 2018 since the new workshop opened after Spring Festival). We can observe the daily productivity of the whole workshop as constant. To simplify the problem further, the efficiency of each production machine could be regarded as the same. So we need to know how many workdays in 2018 and 2019, respectively.</p><p>Excluding new year factory vacation that lasts usually more than one month, but including 2 days before the first shipment after every long vacation, the new workshop has run by convention, there are still 309 workdays in 2018 and 333 workdays in 2019.</p><p>Besides, we still need to find out the initial inventory and final inventory in the warehouse. Unluckily, the manager of the warehouse has never recorded the exact number of the stocked textile rolls after a day of work. He could only roughly remember that at the end of the last day in December the warehouse nearly half full. The standard capacity of the warehouse is around 1000 grey textile rolls. For emergency, it can hold 2000 grey textile rolls but it will impact the daily operations of the factory and increase additional costs. When the warehouse inventory reaches 2500, the warehouse is terribly overloaded and the overfull stacked goods can even compete with people for “oxygen”. So here I have to make a bold assumption that on the night of 2019.12.31 after the last truck left, the final stocked finished goods were 500 rolls.</p><p><em>productivity formula </em>derivation<strong><em>:</em></strong></p><blockquote><strong>approximative</strong> <strong>Daily productivity= annual productivity/ workdays</strong></blockquote><blockquote><strong>annual productivity= final inventory+ annual total delivery- initial inventory</strong></blockquote><blockquote><strong>each machine’s productivity in 2018= each machine’s productivity in 2019</strong></blockquote><blockquote><strong>approximative</strong> <strong>Daily productivity= each machine’s productivity* amount of machines</strong></blockquote><p>Therewith, we can calculate each<strong> machine’s productivity</strong> like the following:</p><blockquote><em>(annual total delivery in 2018+ annual total delivery in 2019 -initial inventory+ final inventory) = (amount of machines in 2018* workdays in 2018+ amount of machines in 2019* workdays in 2019)</em><strong>* <em>each machine</em>’s<em> productivity</em></strong></blockquote><p>The only unknown value is <strong>each machine&#39;s productivity “X”.</strong></p><p>So, the complex question is converted into a simple algebraic equation(<strong>a Basic Linear Equation).</strong></p><p>32609+43109–0+500= (6*309+7*333)*<strong>X</strong></p><p><strong>X</strong>=18.2122 means each machine’s productivity is 18.2122 rolls/ day.</p><blockquote><strong>Daily productivity in 2018 is 109.27 </strong>rolls/ day<strong> and Daily productivity in 2019 is 127.49 </strong>rolls/ day</blockquote><h3>4. calculate the daily stock of finished Product</h3><p>Based on the above-mentioned circumstances, we can confirm that in the year 2018 the factory produced goods 129.27 rolls pro day and in 2019 produced goods 127.49 rolls pro day and during Chinese new year factory vacation 2019.1.20- 2019.2.22 (<strong>excluding 2 days before the first shipment after every long vacation, as above mentioned</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*FwihoLIrA84cq_jM72k7tA.png" /><figcaption>image by Author: a piece of outbound delivery documents of the new workshop in 2019. where a green dash line lies there is a huge time gap, before and after factory vacation.</figcaption></figure><p>It’s easy that we get a data frame recording the daily sum of the delivered goods with Pandas (the related steps are detailed in the Story): <a href="https://towardsdatascience.com/view-a-chinese-factory-from-the-data-aspect-with-python-ad698461f40a">https://towardsdatascience.com/view-a-chinese-factory-from-the-data-aspect-with-python-ad698461f40a</a></p><p>Here I skip the explanation of this part and get the required data frame directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*o_obb4Yxm85VVgl6QYJ6fQ.png" /><figcaption>image by Author: data frame converted from excel file</figcaption></figure><p>The obtained data frame from the excel file is called <em>new_df, </em>by multiplying -1, we get the <em>outbound_df, where minus stands for </em>outbound logistics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*sz-VOm_lsCQB4D3f3byS3A.png" /><figcaption>image by Author: outbound logistics data frame</figcaption></figure><p>now, we should add in each date the daily finished goods quantity, the calculation result is actually inventory in the warehouse.</p><pre><strong>import</strong> <strong>datetime</strong><br><strong>for</strong> i,day <strong>in</strong> enumerate(day_list):<br>  <strong>if</strong> day.start_time == datetime.datetime(2019,1,20):<br>    vacation_start= i<br>  <strong>if</strong> day.year == 2018:<br>    warehouse_df.iloc[i,0]=sum(outbound_df.iloc[0:i+1,0])+109.27*(i+3)<br>  <strong>elif</strong> day.year == 2019 <strong>and</strong> day.start_time &lt; datetime.datetime(2019,1,20):<br>   warehouse_df.iloc[i,0]=sum(outbound_df.iloc[0:i+1,0])+109.27*309+(i-307+3)*127.49<br>  <strong>elif</strong> day.start_time &gt; datetime.datetime(2019,1,20) <strong>and</strong> day.start_time &lt; datetime.datetime(2019,2,22):<br>   warehouse_df.iloc[i,0]=sum(outbound_df.iloc[0:i+1,0])+109.27*309+(vacation_start-307+3)*127.49<br>  <strong>elif</strong> day.start_time &gt; datetime.datetime(2019,2,22):<br>   warehouse_df.iloc[i,0]=sum(outbound_df.iloc[0:i+1,0])+109.27*309+(i-307+3-34)*127.49<br><br>round_warehouse_df= warehouse_df.astype(&#39;int32&#39;)<br>print(round_warehouse_df)</pre><p>After printing the new data frame “round_warehouse_df”, we see the required results on our screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*KNnmSjenjklCq1QdEvR2Qw.png" /><figcaption>image by Author: warehouse inventory data frame, shows how many goods stayed in the warehouse after a day of production and delivery.</figcaption></figure><h3>5. Summary</h3><p>Similarly, we can plot the results with a well-designed style, where two straight lines indicate to us how is the current warehouse loading status. Below the green line means that the warehouse space is abundant, above the red line warns of the overloaded warehouse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HG7U-qV2AW55GNB-whKcpQ.png" /><figcaption>image by Author: warehouse monitoring from 2018 to 2019</figcaption></figure><p>From the above figure, we can take a good overview of the warehouse status over time. With our provided analytics, we can reproduce the usage of the factory warehouse, so that we can better manage the warehouse in the future. In 2018, perhaps lack of experience in warehouse management of the new workshop, the inventory changed drastically. It’s difficult to take warehouse management under control. But in 2019 the factory has stepped into a stable development path. However, with a lack of delivery in October 2019, the warehouse management was once again in a deep crisis. The crisis ended in a month.</p><p>The plot of the monthly delivery can provide evidence to support our judgment. The goods storage crisis was solved after increasing the delivery in the last two months in 2019.</p><p>Therewith, on the last day in 2019, there were only 500 rolls of grey cloth in the warehouse. What a happy ending😀.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXymveXdveZ4NHJCnyC45g.png" /><figcaption>image by Author</figcaption></figure><p>Reviewing our data processing, we used many hypotheses based on knowledge or experience to realize warehouse analysis. It’s important that we should think more about raw data when we get them. By taking a deep look at delivery vouchers, we find an approach to bridge the world of warehouse management.</p><p>At last, please remember that having a lot of data in your hand is great, knowing how to get value out of it can be challenging. Wish you a nice journey in exploring the data around you🌝.</p><h3>6. References</h3><p><a href="https://www.researchgate.net/publication/332375879_Data_Analytics_in_Warehouse_Management_Systems_WMS_Implementations">(PDF) Data Analytics in Warehouse Management Systems (WMS) Implementations</a></p><p><a href="https://d1wqtxts1xzle7.cloudfront.net/49519067/10.1.1.258.6734.pdf?1476165013=&amp;response-content-disposition=inline%3B+filename%3DImpact_of_Warehouse_Management_System_in.pdf&amp;Expires=1609383499&amp;Signature=TDjTjntqiDhUxPEFyvSfkt-CaBGHqj9fG03lh~fgAHf3AKak77993RyB0kII58~gRvJSXtvdjA1o2ka5gHAS6qDH3CfKYZU-usagUg8n1N8gE9RsnAzTgA0gxn2r5A-x8o-G0GzW06PzeldLZtZ7n2G8McOX5FZts1~UYwEYtWDmFJ0yhzwHnbJ6V4C3phBaiPWVVh~sT7uFKxphTU44NJkrtZH6rUZDFPRVPwcMfg251RGmYBcAjB4R5xv2tTP~R-E7tZgKn75BDniLfqTfip9ETHpdtEkd9zIovyChH7n-QgI651klR79lgKoXS6gpvJFLrtN9qQAvO4yle1erJw__&amp;Key-Pair-Id=APKAJLOHF5GGSLRBV4ZA">Ramaa, A., K. N. Subramanya, and T. M. Rangaswamy. “Impact of warehouse management system in a supply chain.” <em>International Journal of Computer Applications</em> 54.1 (2012).</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6a7f44f47af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/data-analytics-helps-warehouse-management-f6a7f44f47af">Data analytics helps warehouse management</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[View a Chinese factory from the data aspect with python]]></title>
            <link>https://medium.com/data-science/view-a-chinese-factory-from-the-data-aspect-with-python-ad698461f40a?source=rss-2b9554572002------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad698461f40a</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Yefeng Xia]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 06:30:55 GMT</pubDate>
            <atom:updated>2020-12-29T15:39:20.795Z</atom:updated>
            <content:encoded><![CDATA[<p>This story is after an <a href="https://yefengxia.medium.com/a-short-interview-about-a-chinese-sweatshop-in-the-textile-industry-aefa9c2229ef">interview</a> with a factory owner, with the help of Pandas to reveal the factory’s face hidden under data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-uotNjKQvUo9ghtw3GFQw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kkchimpy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Karthikeyan K</a> on <a href="https://unsplash.com/s/photos/india-factory?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>1. Background</h3><p>Two months ago, I was in the biggest textile collecting and distributing center in Asia. The City has developed in recent few decades depending on its main industry — Textile. Therewith, I visited a small family factory in the suburbs. The owner of the factory has been managing this factory for more than 30 years. However, he has resisted recording everything that happened in the factory on paper. A modern computer has occurred in the factory just for the last 3 years. The paperless office makes factory management more modern, nevertheless, the data are still not clear enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ux1NJIvhNKSe6dR0i4XFaQ.jpeg" /><figcaption>image by Author: delivery voucher recording 100 grey fabric rolls, each weighs 30 Kg.</figcaption></figure><p>The outbound records of the textile factory in the last 3 years are saved in an Excel file, which contains too much redundant information. <strong>To communicate information clearly and efficiently to readers, I did the following works to realize the data visualization.</strong></p><p>With the help of the few steps below, we can explain the happenings of the factory intuitively. People who have never been there can also have a quick overview of how this textile factory ran in China in the last few years.</p><h3>2. Data availability statements</h3><p>The factory owner is very nice and friendly. A few days later, I received the factory’s outbound delivery data from him. The factory is actually a family sweatshop in the textile industry, whose introduction is in <a href="https://yefengxia.medium.com/a-short-interview-about-a-chinese-sweatshop-in-the-textile-industry-aefa9c2229ef"><strong>my last story</strong></a>, the link also given at the end of this story.</p><p>The main product of the factory is the grey fabric, which is rolled and then transported by truck. Almost every day hundreds of grey fabric rolls are delivered to their customers, who will continue the next chemical treatment process. After going through many industries, the finished textiles land on the market. That is another story that we can hear from others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*owzhT7Oa1gwACtE8-WlBMA.jpeg" /><figcaption>image by Author: a truck driver is checking the cargo loading</figcaption></figure><p>In this story, we just pay attention to data, not industry products. So please don&#39;t think about where the beautiful clothes come from.</p><p>After getting the factory owner’s support and agreement, I’m allowed to publish this story and share the outbound delivery documents in my <a href="https://github.com/Kopfgeldjaeger/Medium_blogs_code/tree/master/3_pandas_factory">GitHub</a>. Additionally, I can give my opinions about the factory after analyzing data.</p><h3>3. Source data explanation</h3><p>It’s an Excel file that records the daily delivery orders for its customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*ZChL50iZBqLfq0zNtCeM1g.jpeg" /><figcaption>image by Author: Excel file overview</figcaption></figure><p>The above screenshot is what we can see as opening the file. Column C relates to customer information so I have to mosaic this part. The two long sheets tell us what happened on each day in the year 2018 and 2019. FAW and type describe what the delivered products look like. However, the essential character of an order is its quantity, which means goods-exchange. For example, the second row in the screenshot records that there are 100 rolls of grey fabric weighed 2500 Kg delivered on 02/28/2018.</p><p><strong>What we should know in advance is that both the factory daily productivity</strong> <strong>and the weight of each grey fabric roll stay almost steady.</strong> This can help us understand the data easily. Actually, the weight of the grey fabric roll depends on its type and FAW. And it can vary from 25 Kg/roll to 30 Kg/roll. It concerns more about professional textile knowledge. To simplify our analysis in this story, I don’t take the light deviation in the weight of fabric rolls into consideration.</p><h3>4. From excel to data frame with pandas</h3><p>Pandas provides a function to import data directly from Excel files, which is a fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the <a href="https://www.python.org/">Python</a> programming language.</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br><strong>from</strong> <strong>matplotlib</strong> <strong>import</strong> <strong>pyplot</strong><br><strong>import</strong> <strong>os</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np      </strong># import necessary packages as usual</pre><p>Since we have two sheets about the year 2018 and 2019, respectively, we can merge two sheets into one data frame with the following code.</p><pre><strong>df2018= pd.read_excel(&quot;outbound.xlsx&quot;,sheet_name=&#39;2018&#39;,header=0)<br>df2019= pd.read_excel(&quot;outbound.xlsx&quot;,sheet_name=&#39;2019&#39;,header=0)<br>frames =[df2018, df2019]<br>df= pd.concat(frames)<br>df</strong></pre><p>We can use the to_datetime() function to create Timestamps from strings in a wide variety of date/time formats, so that the Column ‘date’ can be clearly understood by the computer.</p><pre><strong>df.columns = [&#39;date&#39;,&#39;FAW&#39;,&#39;company&#39;,&#39;type&#39;,&#39;rolls&#39;,&#39;weight&#39;]<br>df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;]) <br>df = df.set_index(&#39;date&#39;)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*fIhVrHk2AvSy1Vk261cRCg.png" /><figcaption>image by Author: data frame first 2 and last 2 rows with shape (675,5)</figcaption></figure><p>Here we illustrate df.head(2) and df.tail(2). The current data frame includes 675 days’ delivery records. It’s obviously not easy for humans to read. So we need to resample Pandas time-series data with the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.resample.html"><strong>resample()</strong></a> function.</p><pre><strong>print(df.resample(&#39;M&#39;).sum().to_period(&#39;M&#39;))</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*HnBWVfUJZ6jKKb2XoPIEdA.png" /><figcaption>image by Author: monthly outbound delivery with the wrong added FAW</figcaption></figure><p>Unfortunately, as we said before, FAW is an attribution of the product, which can not be added together. Therewith, we should pay attention to the correct use of the function.</p><p><strong>The correct code</strong>:</p><pre><strong>print(df.resample(&#39;M&#39;).agg(dict(rolls=&#39;sum&#39;, weight=&#39;sum&#39;)).to_period(&#39;M&#39;))</strong>  #Specify the columns to be summed</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*c6lp_KdcRMKaT5rK4MhoKg.png" /><figcaption>monthly outbound delivery in a correct form</figcaption></figure><p>Similarly, we can also visualize the outbound data specific to each day by a shortcode:</p><pre><strong>new_df=df.resample(&#39;D&#39;).agg(dict(rolls=&#39;sum&#39;, weight=&#39;sum&#39;)).to_period(&#39;D&#39;)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CozMeSJJwC_rb7xSsJ3bmQ.png" /><figcaption>image by Author: daily outbound delivery</figcaption></figure><h3>5. Data plot</h3><p>Finally, we can display the data in an elegant way.</p><pre>fig, ax = plt.subplots(figsize=(18,8))<br>ax= month_df[&#39;weight&#39;].plot(style=&quot;k--&quot;, label=&quot;Series&quot;)<br>ax.set_xlabel(&quot;date&quot;, fontsize=12)<br>ax.set_ylabel(&quot;outbound/Kg&quot;, fontsize=12)<br>ax.set_title(&#39;monthly outbound in year 2018 and 2019&#39;,fontdict={&#39;fontsize&#39;: 14, &#39;fontweight&#39;: &#39;bold&#39;})<br>plt.savefig(&#39;barplot.png&#39;,dpi=100, format=&#39;png&#39;, bbox_inches=&#39;tight&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urewCmbxTmZPEpBl9iWC_w.png" /><figcaption>image by Author: Matplotlib line plot</figcaption></figure><p>There are two obvious troughs on the data chart. This just happened to be what the factory owner said, the factory takes annual factory vacation at the end of the Chinese calendar.</p><p>With the same principle, we can plot the daily outbound delivery. Therewith, I share two interesting links about setting the shape of lines and points: <a href="https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html">https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html</a></p><p><a href="https://matplotlib.org/3.1.1/api/markers_api.html">https://matplotlib.org/3.1.1/api/markers_api.html</a></p><pre>ax= interpolated[&#39;weight&#39;].plot(style=&quot;k--&quot;, label=&quot;Series&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVm1rLCdCML26GPc6101cQ.png" /><figcaption>image by Author: line plot</figcaption></figure><pre>ax= interpolated[&#39;weight&#39;].plot(style=&quot;ks&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hz3n-43SVYcHeiFui2FeVQ.png" /><figcaption>image by Author: point plot</figcaption></figure><p>Through these intuitive plots, we can see the factory’s daily outbound delivery is not as steady as its production plan. As for within a normal working month, the monthly delivery is much more steady, especially between March and December. However, the Chinese new year usually happens between January and February, which means the factory has a long vacation and no delivery record.</p><h3>6. Summary</h3><p>In this story, we have done the basic tasks after we get new data. The origin data is usually saved in an Excel file, so I show the whole process using Pandas to extract information.</p><p>In the end, we visualize the preprocessed data in a proper diagram so that everyone can view the delivery status of the factory without filtering complicated information in the excel table.</p><p>The plot-style is pretty personal. There are many different styles available. Therewith reading more related documents helps us go a long way in data science.</p><h3>7. references (including the previous stories)</h3><ul><li><a href="https://yefengxia.medium.com/a-short-interview-about-a-chinese-sweatshop-in-the-textile-industry-aefa9c2229ef">A short interview about a Chinese sweatshop in the textile industry</a></li><li><a href="https://towardsdatascience.com/how-to-draw-a-bar-graph-for-your-scientific-paper-with-python-a6c2a5e6bcd7">How to draw a bar graph for your scientific paper with python</a></li><li><a href="https://pandas.pydata.org/pandas-docs/stable/index.html">pandas documentation - pandas 2.2.3 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad698461f40a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/view-a-chinese-factory-from-the-data-aspect-with-python-ad698461f40a">View a Chinese factory from the data aspect with python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>