|
| 1 | +--- |
| 2 | +title: 'Data Visualisation' |
| 3 | +teaching: 10 |
| 4 | +exercises: 2 |
| 5 | +--- |
| 6 | + |
| 7 | +:::::::::::::::::::::::::::::::::::::: questions |
| 8 | + |
| 9 | +- How can I use Python tools like Pandas and Plotly to visualize library circulation data? |
| 10 | + |
| 11 | +:::::::::::::::::::::::::::::::::::::::::::::::: |
| 12 | + |
| 13 | +::::::::::::::::::::::::::::::::::::: objectives |
| 14 | + |
| 15 | +- Generate plots using Python to interpret and present data on library circulation. |
| 16 | +- Apply data manipulation techniques with pandas to prepare and transform library circulation data into a suitable format for visualization. |
| 17 | +- Analyze and interpret time-series data by identifying key trends and outliers in library circulation data. |
| 18 | + |
| 19 | +:::::::::::::::::::::::::::::::::::::::::::::::: |
| 20 | + |
| 21 | +For this module, we will use a different version of our circulation data that is in a tidy data format, where each variable forms a column, each observation forms a row, and each type of observation unit forms a row. If your workshop included the Tidy Data episode, you should be set and have an object called `df_long` in your Jupyter environment. If not, we’ll read that dataset in now, as it was provided for this lesson. |
| 22 | + |
| 23 | + |
| 24 | +``` python |
| 25 | +#import if it is already not |
| 26 | +import pandas as pd |
| 27 | +``` |
| 28 | + |
| 29 | +If `df_long` isn’t loaded already, we can read it in using `read_csv`. Note, if it isn’t present in your local `data/` folder. |
| 30 | + |
| 31 | +``` python |
| 32 | +df_long = pd.read_csv('data/circ_long.tsv', sep="\t") |
| 33 | +``` |
| 34 | + |
| 35 | +We are using a couple of new parameters in our `read_csv` function above. Since the file we want to read in is a tab-separated values (TSV) file, we tell our `read_csv` function that using the `sep="\t"` parameter. `\t` is encoding for tab character in Python. Other separators or delimeters could include `|` or `;` depending on your data file. |
| 36 | + |
| 37 | +Let’s look at the data: |
| 38 | + |
| 39 | +``` python |
| 40 | +df_long.head() |
| 41 | +``` |
| 42 | + |
| 43 | +``` output |
| 44 | + branch address ... circulation date |
| 45 | +0 Albany Park 5150 N. Kimball Ave. ... 8427 2011-01-01 |
| 46 | +1 Altgeld 13281 S. Corliss Ave. ... 1258 2011-01-01 |
| 47 | +2 Archer Heights 5055 S. Archer Ave. ... 8104 2011-01-01 |
| 48 | +3 Austin 5615 W. Race Ave. ... 1755 2011-01-01 |
| 49 | +4 Austin-Irving 6100 W. Irving Park Rd. ... 12593 2011-01-01 |
| 50 | +``` |
| 51 | + |
| 52 | + |
| 53 | +In order to plot this data over time we need to do two things to prepare it first. First, we need to tell Python that the data column is a datetime object using the Pandas `to_dateime` function. Second, we assign the date column as our index for the data. These two steps will set up our data for plotting. |
| 54 | + |
| 55 | +``` python |
| 56 | +df_long['date']= pd.to_datetime(df_long['date']) |
| 57 | +``` |
| 58 | + |
| 59 | +The above converts our date column to a data time object. Let’s confirm it worked. |
| 60 | + |
| 61 | +``` python |
| 62 | +df_long.info() |
| 63 | +``` |
| 64 | + |
| 65 | + |
| 66 | +``` output |
| 67 | +<class 'pandas.core.frame.DataFrame'> |
| 68 | +RangeIndex: 11556 entries, 0 to 11555 |
| 69 | +Data columns (total 9 columns): |
| 70 | +# Column Non-Null Count Dtype |
| 71 | + --- ------ -------------- ----- |
| 72 | + 0 branch 11556 non-null object |
| 73 | + 1 address 7716 non-null object |
| 74 | + 2 city 7716 non-null object |
| 75 | + 3 zip code 7716 non-null float64 |
| 76 | + 4 ytd 11556 non-null int64 |
| 77 | + 5 year 11556 non-null int64 |
| 78 | + 6 month 11556 non-null object |
| 79 | + 7 circulation 11556 non-null int64 |
| 80 | + 8 date 11556 non-null datetime64[ns] |
| 81 | +dtypes: datetime64[ns](1), float64(1), int64(3), object(4) |
| 82 | +memory usage: 812.7+ KB |
| 83 | +``` |
| 84 | + |
| 85 | +That worked! Now, we can make this datetime object our dataframe index. |
| 86 | + |
| 87 | + |
| 88 | +``` python |
| 89 | +df_long.set_index('date', inplace=True) |
| 90 | +``` |
| 91 | + |
| 92 | +If we look at the data again, we will see our index will be set to date. |
| 93 | + |
| 94 | +``` python |
| 95 | +df_long.head() |
| 96 | +``` |
| 97 | + |
| 98 | +``` output |
| 99 | + branch address ... month circulation |
| 100 | + date ... |
| 101 | + 2011-01-01 Albany Park 5150 N. Kimball Ave. ... january 8427 |
| 102 | + 2011-01-01 Altgeld 13281 S. Corliss Ave. ... january 1258 |
| 103 | + 2011-01-01 Archer Heights 5055 S. Archer Ave. ... january 8104 |
| 104 | + 2011-01-01 Austin 5615 W. Race Ave. ... january 1755 |
| 105 | + 2011-01-01 Austin-Irving 6100 W. Irving Park Rd. ... january 12593 |
| 106 | +
|
| 107 | +``` |
| 108 | + |
| 109 | +Ok! We are now ready to plot our data. Since this data is monthly data, we can plot the circulation data over time. |
| 110 | + |
| 111 | +At first, let’s focus on a specific branch. We can select the rows for the Albany Park branch: |
| 112 | + |
| 113 | +``` python |
| 114 | +albany = df_long[df_long['branch'] == 'Albany Park'] |
| 115 | +``` |
| 116 | + |
| 117 | +``` python |
| 118 | +albany.head() |
| 119 | +``` |
| 120 | + |
| 121 | +``` output |
| 122 | + branch address ... month circulation |
| 123 | + date ... |
| 124 | + 2011-01-01 Albany Park 5150 N. Kimball Ave. ... january 8427 |
| 125 | + 2016-01-01 Albany Park NaN ... january 10905 |
| 126 | + 2017-01-01 Albany Park NaN ... january 11031 |
| 127 | + 2022-01-01 Albany Park 3401 W. Foster Ave. ... january 5561 |
| 128 | + 2018-01-01 Albany Park NaN ... january 9381 |
| 129 | +``` |
| 130 | + |
| 131 | +Now we can use the `plot()` function built into pandas. Let’s try it: |
| 132 | + |
| 133 | +``` python |
| 134 | +albany.plot() |
| 135 | +``` |
| 136 | + |
| 137 | + |
| 138 | + |
| 139 | +That’s great! By default `plot` use a line plot and will plot all numeric variables of the data frame. This isn’t exactly what we want, so let’s tell `plot` what variable to use by selecting `circulation_count`. |
| 140 | + |
| 141 | + |
| 142 | +``` python |
| 143 | +albany['circulation'].plot() |
| 144 | +``` |
| 145 | + |
| 146 | + |
| 147 | + |
| 148 | +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: challenge |
| 149 | + |
| 150 | +## Analyze the Circulation Trends |
| 151 | + |
| 152 | +Examine the line graph depicting library circulation data. You will notice two significant periods where the circulation drops to zero: first in March 2020 and then a two-year zero circulation period starting in 2012. Evaluate the graph and identify any trends, unusual patterns, or notable changes in the data. |
| 153 | + |
| 154 | +::::::::::::::::::::::::::::::::::::::::::::::::::: solution |
| 155 | + |
| 156 | +The significant drop in circulation in March 2020 is likely due to the COVID-19 pandemic, which caused widespread temporary closures of public spaces, including libraries. |
| 157 | + |
| 158 | +The drop from 2012 through part of 2014 corresponds to the reconstruction period of the Albany Park Branch. The original building at 5150 N. Kimball Avenue was demolished in 2012, and a new, modern building was constructed at the same site. The new Albany Park Branch opened on September 13, 2014, at 3104 W. Foster Avenue in the North Park neighborhood of Chicago. More details about this renovation can be found on the Chicago Public Library webpage: [Chicago Public Library - Albany Park](https://www.chipublib.org/news/stories-we-tell-albany-park-exhibit/). |
| 159 | +:::::::::::::::::::::::::::::::::::::::::::::::: |
| 160 | +:::::::::::::::::::::::::::::::::::::::::::::::: |
| 161 | + |
| 162 | +What if we want to alter the axis labels and the title of the graph. In order to do that, we need to first import `matplotlib`, an extensive plotting package in Python that lets us alter all aspects of a graph. |
| 163 | + |
| 164 | +``` python |
| 165 | +# the plotting package pandas is using under the hood to `plot()` |
| 166 | +import matplotlib.pyplot as plt |
| 167 | + |
| 168 | +albany['circulation'].plot(title='Circulation Count Over Time', figsize=(10, 5), color='blue') |
| 169 | +# Adding labels and showing the plot |
| 170 | +plt.xlabel('Date') |
| 171 | +plt.ylabel('Circulation Count') |
| 172 | +plt.show() |
| 173 | +``` |
| 174 | + |
| 175 | + |
| 176 | +What if we want to use a different plot type for this graphic? To do so, we can change the `kind` parameters in our `plot` function. |
| 177 | + |
| 178 | +``` python |
| 179 | +albany['circulation'].plot(kind='area', title='Circulation Count Area Plot at Albany Park', alpha=0.5) |
| 180 | +plt.xlabel('Date') |
| 181 | +plt.ylabel('Circulation Count') |
| 182 | +plt.show() |
| 183 | +``` |
| 184 | + |
| 185 | + |
| 186 | +We can also look at our circulation data as a histogram. |
| 187 | + |
| 188 | +``` python |
| 189 | +albany['circulation'].plot(kind='hist', bins=20, title='Distribution of Circulation Counts at Albany Park') |
| 190 | +plt.xlabel('Circulation Count') |
| 191 | +plt.show() |
| 192 | +``` |
| 193 | + |
| 194 | + |
| 195 | + |
| 196 | +## Interactive Line Plot for Circulation Over Time |
| 197 | + |
| 198 | +Let’s switch back to the full dataframe in `df_long` and use another |
| 199 | +plotting package in Python called Plotly. First let’s install and then use |
| 200 | +the package. |
| 201 | + |
| 202 | +```{python} |
| 203 | +# uncomment below to install plotly if the import fails. |
| 204 | +# !pip install plotly |
| 205 | +import plotly.express as px |
| 206 | +``` |
| 207 | +Now we can visualize how circulation counts have changed over time for selected |
| 208 | +branches. This can be especially useful for identifying trends, |
| 209 | +seasonality, or anomalies. We will first create a subset of our data and |
| 210 | +only look at branches starting with the letter A. Feel free to select |
| 211 | +different branches. After subsetting, we will sort our new dataframe by |
| 212 | +date and then plot our data by date and ciculation count. |
| 213 | + |
| 214 | +``` python |
| 215 | +# Creating a line plot for a few selected branches to avoid clutter |
| 216 | +selected_branches = df_long[df_long['branch'].isin(['Altgeld', |
| 217 | + 'Archer Heights', |
| 218 | + 'Austin', |
| 219 | + 'Austin-Irving', |
| 220 | + 'Avalon'])] |
| 221 | +selected_branches = selected_branches.sort_values(by='date') |
| 222 | +``` |
| 223 | + |
| 224 | +``` python |
| 225 | +fig = px.line(selected_branches, x=selected_branches.index, y='circulation', color='branch', title='Circulation Over Time for Selected Branches') |
| 226 | +fig.show() |
| 227 | +``` |
| 228 | +TODO: include either a static, gif, or html output of plotly |
| 229 | +* https://plotly.com/python/interactive-html-export/ |
| 230 | +* https://pypi.org/project/plotly-gif/ |
| 231 | + |
| 232 | +Plotly provides some nice interactive features out of the box. Hover |
| 233 | +over the data and interact witht he plot controls. |
| 234 | + |
| 235 | +#### Barplot to Compare Circulation Distributions Among Branches |
| 236 | + |
| 237 | +Let’s use a barplot to compare the distribution of circulation counts |
| 238 | +among branches. We first need to group our data by branch and sum up the |
| 239 | +circulation counts. Then we can use the bar plot to show the |
| 240 | +distribution of total circulation over branches. |
| 241 | + |
| 242 | +``` python |
| 243 | +# Aggregate circulation by branch |
| 244 | +total_circulation_by_branch = df_long.groupby('branch')['circulation'].sum().reset_index() |
| 245 | + |
| 246 | +# Create a bar plot |
| 247 | +fig = px.bar(total_circulation_by_branch, x='branch', y='circulation', title='Total Circulation by Branch') |
| 248 | +fig.show() |
| 249 | +``` |
| 250 | +TODO: include either a static, gif, or html output of plotly |
| 251 | +* https://plotly.com/python/interactive-html-export/ |
| 252 | +* https://pypi.org/project/plotly-gif/ |
| 253 | + |
| 254 | +::: keypoints |
| 255 | +- Explored the use of pandas for basic data manipulation, ensuring correct indexing with DatetimeIndex to enable time-series operations like resampling. |
| 256 | +- Used pandas’ built-in plot() for initial visualizations and faced issues with overplotting, leading to adjustments like data filtering and resampling to simplify plots. |
| 257 | +- Introduced Plotly for advanced interactive visualizations, enhancing user engagement through dynamic plots such as line graphs, area charts, and bar plots with capabilities like dropdown selections. |
| 258 | +::: |
0 commit comments