Python US Census API Tutorial (Part V) - Top 5 U.S. State Populations in Bar Chart

Veröffentlicht am: 11 September 2023
auf dem Kanal: Roman's Coding Tutorials
105
3

Link to census data tables:
https://api.census.gov/data/2015/acs/...

Tutorial code:
1 import matplotlib.pyplot as plt
2 from us.states import lookup
3 from census import Census
4 import pandas as pd
5 from os import getenv
6 import random # Import the random module to generate random colors
7
8 # Grab census data
9 c = Census(getenv("CENSUS_API_KEY"))
10 data = c.acs5.state("B01001_001E", Census.ALL)
11 formatted_data = []
12
13 # Extract population data for each state
14 for entry in data:
15 state = lookup(entry["state"]).abbr
16 pop = entry.pop("B01001_001E")
17 formatted_data.append({"state": state, "POP": pop})
18
19 # Create a DataFrame
20 census_dataframe = pd.DataFrame(formatted_data)
21
22 # Sort the DataFrame by population in descending order
23 census_dataframe.sort_values(by="POP", ascending=False, inplace=True)
24
25 # Select the top 5 most populous states
26 top_states = census_dataframe.head(5)
27
28 # Generate random colors for the bars
29 bar_colors = [plt.cm.viridis(random.random()) for _ in range(len(top_states))]
30
31 # Plot the population of the top 5 states using Matplotlib with different colors
32 plt.figure(figsize=(10, 6))
33 plt.bar(top_states["state"], top_states["POP"], color=bar_colors)
34 plt.xlabel("State")
35 plt.ylabel("Population")
36 plt.title("Top 5 Most Populous States in the US")
37 plt.xticks(rotation=45)
38 plt.show()

Soundtrack:

"A Vibe Nostalgic" by Mindseye
https://freemusicarchive.org/music/Mi...
Beyond cropping a snippet from the full song, no changes were made to this content.

Bar Chart Video Clip at Start:
https://pixabay.com/videos/line-graph...


Auf dieser Seite können Sie das Online-Video Python US Census API Tutorial (Part V) - Top 5 U.S. State Populations in Bar Chart mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Roman's Coding Tutorials 11 September 2023 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 105 Mal angesehen und es wurde von 3 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!