''' DS2000 Spring 2022 Practice with plotly First (one time), make a new anaconda environment. - then, search for "plotly" in the uninstalled list, and install it Next (every time we need it) - import plotly.io as pio - from plotly.offline import plot - import plotly.express as px - Make a line chart with px.line() and then save the object it returns as fig - use fig's methods to customized the plot (fig.update_traces(), fig.update_layout(), etc.) - call plot(fig) to render the interactive chart in your browser Plotly does a lot of other cool stuff beyond these examples! https://plotly.com/python/plotly-express/ ''' import pandas as pd import matplotlib.pyplot as plt import plotly.io as pio from plotly.offline import plot import plotly.express as px PREZ = "1976-2020-president.csv" def main(): # Step one -- read from the file df = pd.read_csv(PREZ, sep = "\t") # Take a look at the first few rows print(df.head(20)) # What are all the columns? print("\nColums are...") print(df.columns) # Get the summary stats for each column print(df.describe()) # What are the datatypes of each column? print(df.dtypes) # Keep only the columns I like # Def need year, state, party, and num votes # don't strictly need candidate name, just for Laney df = df[["year", "state", "candidate", "party_simplified", "candidatevotes"]] print("\nDF with only a few columns...") print(df.head(20)) # Print just the candidate names print(df["candidate"].head(50)) # Gather all of the vote data per year, per party df = df.groupby(["year", "party_simplified"]).sum().reset_index() print("\nAfter grouping by year/party...") print(df.head(30)) # Keep only dem/rep party rows df = df[(df["party_simplified"] == "DEMOCRAT") | (df["party_simplified"] == "REPUBLICAN")] print("\nThis should be just dems/reps...") print(df.head(30)) # Make an interactive plot with plotly! pio.renderers.default = "browser" fig = px.line(x = df["year"], y = df["candidatevotes"], color = df["party_simplified"]) fig.update_traces(mode = "markers+lines", hovertemplate = None) fig.update_layout(hovermode = "x unified") plot(fig) main()