How Do I Use A For Loop And The Zip Function To Plot Subplots In Python?
I'm new to python and stuck on using the zip function to plot subplots. Help is highly appreciated!!
I would like to plot bar charts for my nutrients in the dataframe, where I can distinguish between organic and non-organic. For each country in my dataframe I want subplots. This is my dataframe:
And this is how my plot should look like:
As I have many countries in my dataframe, I would like to us a for loop and the zip function. But i get an empty canvas when I implement this code:
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(30, 15)) for i, ax in zip(range(0, 5), axes.flatten()): # Filter data for each country country_df = df[df["country"] == i] # Populate subplots ax.bar(country_df["nutrients"], country_df["values"], hue="organic") # Add x/y labels ax.set_xlabel("nutrients") ax.set_ylabel("average value")
Can somebody help? Thanks!!
The problem with your code is when you try to filter by country, but you are actually filtering by a number (which will never match your plots). To easily create the grouping you show in the figure, I recommend using
seaborn. A possible solution can be:
import seaborn as sns countries = set(df['countries']) # Calculate the number of subplots based on the number of countries ncols = 3 nrows = math.ceil(len(countries) / ncols) fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(30, 15)) for country, ax in zip(countries, axes.flatten()): # Filter data for each country country_df = df[df["country"] == country] # Select by country name # Populate subplots sns.barplot(data=country_df, x="nutrients", y="values", hue="organic", ax=ax) # Add x/y labels ax.set_xlabel("nutrients") ax.set_ylabel("average value")
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module