Skip to content

Commit

Permalink
Addition of the python line styling
Browse files Browse the repository at this point in the history
Desired nonexistent pages of R only code showed styling line plots as needing some Python contributions, so added seaborn.objects styling into this section plus the 2x2 grid of it. Basically a replica of what follows in R (except it had to be aggregated per year because seaborn.object is still... odd... with dates :[  )
  • Loading branch information
RommelArtola committed Aug 20, 2024
1 parent 49c58f8 commit f2ec2de
Show file tree
Hide file tree
Showing 2 changed files with 126 additions and 0 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
126 changes: 126 additions & 0 deletions Presentation/Figures/styling_line_graphs.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,132 @@ There are several ways of styling line graphs. The following examples demonstrat

# Implementation

## Python
```python
import pandas as pd
import seaborn.objects as so
import numpy as np
import matplotlib.pyplot as plt

# Download the economics dataset (from ggplot2 so comparison is apples-to-apples)
url = "https://raw.githubusercontent.com/tidyverse/ggplot2/main/data-raw/economics.csv"
economics = pd.read_csv(url)

# Disclaimer on seaborn.objects.
"""
seaborn.objects is still under development.. Which means some things are sub-optimal
This includes how it handles datetime x-variables, for example.
It skips far too many years on the xticks, so, a way around that,
is to manually extract just the year value from the date column
and plot that. However, that would mean you have to aggregate per year, which could be
not what you want.
"""
df = (
economics
.assign(
date = lambda df: pd.to_datetime(df['date']),
year = lambda df: df['date'].dt.year
)
.groupby(by='year')
.aggregate(
Mean_Unemploy = ('unemploy', 'mean'),
Mean_psavert = ('psavert', 'mean'),
Mean_unempmed = ('uempmed', 'mean')
)
.reset_index()
)


# Basic Plot with the most basic renamings
p1 = (
so.Plot(data=df, x='year', y='Mean_unempmed')
.add(so.Line())

)

p1




## Change line color and chart labels
## Note here that color is inside of the Line call, so this would color the line.
## If color were instead *inside* the so.Plot() object, SO would assign it
## a different line for each value of the factor variable (column), colored differently.
# Howeever, in our case, we can pass a color directly.
p2 = (
so.Plot(data=df, x='year', y='Mean_unempmed')
.add(so.Line(color='purple'))
.label(title='Annual avg of median unemployment duration', x='Year', y='Mean Unemployed')

)

p2





## plotting multiple charts (of different line types and sizes)
p3 = (
so.Plot(data=df)
.add(so.Line(color='darkblue', linewidth=5), x='year', y='Mean_unempmed')
.add(so.Line(color='red', linewidth=2, linestyle='dotted'), x='year', y='Mean_psavert')
.label(title='Economics',
x='Year',
y='')

)

p3


## Plotting a different line type for each group
## There isn't a natural factor in this data so let's just duplicate the data and make one up
df['fac'] = 1

df2 = df.copy()

df2['fac'] = 2

df2['Mean_unempmed'] = df2['Mean_unempmed'] - 2 + np.random.normal(size=len(df2))

df_final = pd.concat([df, df2], ignore_index=True).astype({'fac':'category'})


p4 = (
so.Plot(data=df_final, x='year', y='Mean_unempmed', color='fac')
.add(so.Line())
.label(title = "Median Duration of Unemployment",
x = "Date",
y = "",
color='Random Factor')
)

p4



# Plot all 4 plots
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
# Draw each plot in the corresponding subplot
p1.on(axs[0, 0]).plot()
p2.on(axs[0, 1]).plot()
p3.on(axs[1, 0]).plot()
p4.on(axs[1, 1]).plot()

# Adjust layout to avoid overlap
plt.tight_layout()

# Show the combined plot
plt.show()
```
The four plots generated by the code are (in order p1, p2, then p3 and p4):

![Four Styled Line Graphs in Python]({{ "/Presentation/Figures/Images/Styling-Line-Graphs/styling_line_graphs_Python.png" | relative_url }})



## R
```r
## If necessary
Expand Down

0 comments on commit f2ec2de

Please sign in to comment.