{"id":1204,"date":"2020-08-07T14:58:31","date_gmt":"2020-08-07T21:58:31","guid":{"rendered":"http:\/\/blog.nillsf.com\/?p=1204"},"modified":"2020-08-07T14:58:34","modified_gmt":"2020-08-07T21:58:34","slug":"adding-x-axis-to-matplotlib-plots-in-jupyter-notebooks","status":"publish","type":"post","link":"https:\/\/blog.nillsf.com\/index.php\/2020\/08\/07\/adding-x-axis-to-matplotlib-plots-in-jupyter-notebooks\/","title":{"rendered":"Adding x-axis to matplotlib plots in Jupyter notebooks"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">I&#8217;ve blogged before about how I&#8217;m doing some of <a href=\"https:\/\/blog.nillsf.com\/index.php\/2020\/07\/21\/how-im-doing-my-own-covid-19-data-analysis-using-jupyter-python-pandas-and-matplotlib\/\">my own data analysis<\/a> on the COVID-19 numbers. One thing that I didn&#8217;t like about my graphs was that they didn&#8217;t contain an x-axis, which made them a little bit harder to read. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this (very quick) blog post I&#8217;ll show you how to add an x-axis to a matplotlib plot.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Preparation for the graph<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s start with the data we&#8217;ll use for this graph. If you want more information about these intro steps, please refer to my <a href=\"https:\/\/blog.nillsf.com\/index.php\/2020\/07\/21\/how-im-doing-my-own-covid-19-data-analysis-using-jupyter-python-pandas-and-matplotlib\/\">previous post<\/a>. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>%matplotlib inline\nimport matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>cases = pd.read_csv('https:\/\/raw.githubusercontent.com\/CSSEGISandData\/COVID-19\/master\/csse_covid_19_data\/csse_covid_19_time_series\/time_series_covid19_confirmed_US.csv')\ncases_clean = cases&#91;cases&#91;\"Province_State\"] == \"California\"].set_index(\"Admin2\").T.drop(&#91;'UID','iso2','iso3','code3','FIPS','Province_State','Country_Region','Lat','Long_','Combined_Key'])<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now that we have a cases dataset, we can plot that dataset. In my case, I&#8217;m interested in 4 counties, so we&#8217;ll filter by those four counties:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>counties = &#91;'Alameda',\n             'San Francisco',\n             'San Mateo',\n             'Santa Clara']<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>plot = cases_clean&#91;counties].plot(figsize=(20,10))\nplot.set_title(\"COVID-19 cases in Bay Area Counties\")<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This returns a plot that looks like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1006\" height=\"550\" src=\"\/wp-content\/uploads\/2020\/08\/image-7.png\" alt=\"\" class=\"wp-image-1206\" srcset=\"https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-7.png 1006w, https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-7-300x164.png 300w, https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-7-768x420.png 768w, https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-7-750x410.png 750w\" sizes=\"auto, (max-width: 1006px) 100vw, 1006px\" \/><figcaption>The original graph without x-axis labels.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, the x-asis is empty. Let&#8217;s try to fix this. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Adding an x-axis and labels<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When it comes to the x-axis in matplotlib, there&#8217;s two important pieces to that axis:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>x-ticks: The place in the dataset where you want a label to be applied<\/li><li>x-ticks-labels: The label you want to put at the tick<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Practically in our case, I believe it would be interesting to show 10 dates along the x-axis. This means that we&#8217;ll need to generate two objects to pass to matplotlib:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>x-ticks: 10 equally spaced tick labels. <\/li><li>x-labels: The labels we want to pass<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For the first, we can use the <code>np.arange()<\/code> function. For the second, we can use a slice of the original dataframe. To get that slice, we can use the ticks array. These ticks are of the float type, which we&#8217;ll need to convert to integer to get them to work as a slide.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ticks = np.arange(0,len(cases_clean.index),len(cases_clean.index)\/10)\nlabels = cases_clean.index&#91;ticks.astype(int)]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We can now use these two objects to create the ticks and the labels on the graph. Please note, that to update the graph, you&#8217;ll need to make all of this part of the cell that generates the graph.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>_ = plot.xaxis.set_ticks(ticks)\n_ = plot.xaxis.set_ticklabels(labels)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><em>short note: the <code>_ =<\/code> is optional, but it avoids verbose output in the notebook.<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">All of this results in a figure that looks like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"624\" src=\"\/wp-content\/uploads\/2020\/08\/image-8-1024x624.png\" alt=\"\" class=\"wp-image-1207\" srcset=\"https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-8-1024x624.png 1024w, https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-8-300x183.png 300w, https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-8-768x468.png 768w, https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-8.png 1027w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Bonus: create graphs of the last X days<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, this graph goes all the way back to January. Maybe, you&#8217;re most interested in the data from the past X days. It&#8217;s pretty straightforward to adapt this python code to reflect data from the past e.g. 100 days by using the <code>tail()<\/code> function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>plot = cases_clean&#91;counties].tail(100).plot(figsize=(20,10))\nplot.set_title(\"COVID-19 cases in Bay Area Counties in last 100 days.\")\n\nticks = np.arange(0,len(cases_clean.tail(100).index),len(cases_clean.index)\/10)\nlabels = cases_clean.tail(100).index&#91;ticks.astype(int)]\n\n_ = plot.xaxis.set_ticks(ticks)\n_ = plot.xaxis.set_ticklabels(labels)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Which will results in the following graphic:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1007\" height=\"629\" src=\"\/wp-content\/uploads\/2020\/08\/image-9.png\" alt=\"\" class=\"wp-image-1208\" srcset=\"https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-9.png 1007w, https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-9-300x187.png 300w, https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-9-768x480.png 768w\" sizes=\"auto, (max-width: 1007px) 100vw, 1007px\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">And as you can see, the x-axis automatically adjusted (well, not automatically, we need to add the tail function there as well). <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This was a short and quick post explaining how to add an x-axis and labels to a matplotlib graph in a Python notebook. I hope you find this useful. If you generate any interesting graphs, don&#8217;t hesitate to share them with me on either Twitter or LinkedIn! <\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;ve blogged before about how I&#8217;m doing some of my own data analysis on the COVID-19 numbers. One thing that I didn&#8217;t like about my graphs was that they didn&#8217;t contain an x-axis, which made them a little bit harder to read. In this (very quick) blog post I&#8217;ll show you how to add an [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1207,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[47],"tags":[134,74,44,136,137,135,114],"class_list":["post-1204","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-science","tag-covid-19","tag-data-engineering","tag-data-science","tag-jupyter","tag-matplotlib","tag-pandas","tag-python"],"jetpack_featured_media_url":"https:\/\/nillsfblog.blob.core.windows.net\/media\/2020\/08\/image-8.png","_links":{"self":[{"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/posts\/1204","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/comments?post=1204"}],"version-history":[{"count":1,"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/posts\/1204\/revisions"}],"predecessor-version":[{"id":1209,"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/posts\/1204\/revisions\/1209"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/media\/1207"}],"wp:attachment":[{"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/media?parent=1204"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/categories?post=1204"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.nillsf.com\/index.php\/wp-json\/wp\/v2\/tags?post=1204"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}