Chat With ChatGPT - An Interactive Conversational AI

User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#21

Grouped Bar Charts from Pandas Dataframe


1. Grouped Bar Charts: 100% Distribution Across Groups

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. import textwrap
  6. from textwrap import wrap
  7. textstr = 'Created at \nwww.tssfl.com'
  8.  
  9. #Create a random dataframe
  10. group_names = np.random.choice(['Group A', 'Group B', 'Group C', 'Group D', 'Group E', 'Group F', 'Group G'], size=100)
  11. responses = np.random.choice(['agree', 'disagree', 'strongly agree', 'strongly disagree'], size=100)
  12. df = pd.DataFrame({'Column1': group_names, 'Column2': responses})
  13.  
  14.  
  15. #Convert dataframe to preserve the original order of responses.
  16. df = pd.crosstab(df['Column1'], df['Column2'])
  17.  
  18. #Convert pandas dataframe to numpy array
  19. data = df.to_numpy()
  20.  
  21. #Calculate the total percentage for each group
  22. group_totals = np.sum(data, axis=1)
  23. total = np.sum(group_totals)
  24.  
  25. #Convert the list to a pandas Series
  26. group_series = pd.Series(group_names)
  27. #Extract unique values only - NumPy array
  28. group_names = group_series.unique()
  29.  
  30. response_series = pd.Series(responses)
  31. responses = response_series.unique()
  32.  
  33. #Plot grouped bar charts
  34. fig, ax = plt.subplots(figsize=(14,7))
  35. bar_width = 0.1
  36. opacity = 0.8
  37.  
  38. colors = ['green', 'crimson', '#00FF00', "#FFD700", 'blue', '#4286f4', "#FF4500"]
  39.  
  40. for i, group_data in enumerate(data):
  41.     x = np.arange(len(responses))
  42.     bars = ax.bar(x + i * bar_width, group_data, bar_width,
  43.                   alpha=opacity, color=colors[i], label=group_names[i], align='edge')
  44.  
  45.     #Add percentage annotations for each bar
  46.     for j, bar in enumerate(bars):
  47.         percentage = '{:.2f}%'.format(100 * bar.get_height() / total)
  48.         frequency = str(int(bar.get_height()))
  49.         x_pos = bar.get_x() + bar.get_width() / 2
  50.         y_pos = bar.get_height()
  51.         ax.annotate(percentage, (x_pos, y_pos), rotation=90, xytext=(0, 15),
  52.                     textcoords="offset points", ha="center", va="bottom", color='red')
  53.         if y_pos >= 0:
  54.             ax.annotate(frequency, (x_pos, y_pos), rotation=0, xytext=(0, 7),
  55.                         textcoords="offset points", ha="center", va="center", color='green')
  56.  
  57. ax.spines['top'].set_visible(False)
  58. #Set axis labels and title
  59. ax.set_xlabel('Responses')
  60. ax.set_ylabel('Frequency')
  61. ax.set_title('Grouped Bar Charts: Frequency and 100% Distribution Across Groups', size=12, pad=40)
  62.  
  63. #Set x-axis tick labels
  64. ax.set_xticks(x + (len(group_names) - 1) * bar_width / 2)
  65. ax.set_xticklabels(responses)
  66.  
  67. #Wrap column titles for legend, break long column titles after 20 characters for legend titles
  68. #legend_title = "\n".join(textwrap.wrap(df.columns[2], 20))
  69. #legend_title = "\n".join(textwrap.wrap(column2, 30))
  70.  
  71. #Create a legend box outside the plot area
  72. legend = plt.legend(title='Legend', bbox_to_anchor=(1.05, 1), loc='upper left')
  73. plt.subplots_adjust(right=0.9)  #Adjust the right margin to accommodate the legend
  74.  
  75. #Add the text annotation outside the plot area
  76. #plt.figtext(0.1, 0.5, textstr, fontsize=10, verticalalignment='center')
  77. plt.gcf().text(0.02, 0.94, textstr, fontsize=14, color='green')
  78.  
  79. plt.tight_layout()
  80. plt.show()
  81.  
  82. """
  83. #Calculate the total number for each group in Column1
  84. group_counts = df['Column1'].value_counts()
  85.  
  86. #Convert the Series to a NumPy array
  87. group_totals = group_counts.values
  88. """


Horizontal Bar Charts

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. textstr = 'Created at \nwww.tssfl.com'
  5.  
  6. # Create a random dataframe
  7. group_names = np.random.choice(['Group A', 'Group B', 'Group C', 'Group D', 'Group E', 'Group F', 'Group G'], size=100)
  8. responses = np.random.choice(['agree', 'disagree', 'strongly agree', 'strongly disagree'], size=100)
  9. df = pd.DataFrame({'Column1': group_names, 'Column2': responses})
  10.  
  11. #Convert dataframe to preserve the original order of responses.
  12. df = pd.crosstab(df['Column1'], df['Column2'])
  13.  
  14. #Convert pandas dataframe to numpy array
  15. data = df.to_numpy()
  16.  
  17. # Calculate the total percentage for each group
  18. group_totals = np.sum(data, axis=1)
  19. total = np.sum(group_totals)
  20.  
  21. #Convert the list to a pandas Series
  22. group_series = pd.Series(group_names)
  23. #Extract unique values only - NumPy array
  24. group_names = group_series.unique()
  25. group_names = group_names[::-1]  #Reverse the order of group labels
  26.  
  27. response_series = pd.Series(responses)
  28. responses = response_series.unique()
  29.  
  30. # Plot grouped bar charts
  31. fig, ax = plt.subplots(figsize=(10, 10))
  32. bar_width = 0.1
  33. opacity = 0.8
  34.  
  35. colors = ['green', 'crimson', '#00FF00', "#FFD700", 'blue', '#4286f4', "#FF4500"]
  36. colors = colors[:len(group_names)][::-1]  # Reverse the order of colors and limit to the number of groups
  37.  
  38. for i, group_data in enumerate(data):
  39.     x = np.arange(len(responses))
  40.     bars = ax.barh(x + i * bar_width, group_data, bar_width,
  41.                    alpha=opacity, color=colors[i], label=group_names[i])
  42.  
  43.     # Add percentage annotations for each bar
  44.     for j, bar in enumerate(bars):
  45.         percentage = '{:.2f}%'.format(100 * bar.get_width() / total)
  46.         frequency = str(int(bar.get_width()))
  47.         y_pos = bar.get_y() + bar.get_height() / 2
  48.         x_pos = bar.get_width()
  49.         ax.annotate(percentage, (x_pos, y_pos), xytext=(12, 0),
  50.                     textcoords="offset points", ha="left", va="center", color='red')
  51.        
  52.         if x_pos >= 0:
  53.             ax.annotate(frequency, (x_pos, y_pos), rotation=0, xytext=(6, 0),
  54.                         textcoords="offset points", ha="center", va="center", color='green')
  55.        
  56.  
  57. ax.spines['right'].set_visible(False)
  58. # Set axis labels and title
  59. ax.set_xlabel('Frequency')
  60. ax.set_ylabel('Responses')
  61. ax.set_title('Grouped Bar Charts: Frequency and 100% Distribution for Each Group', size=12, pad=20)
  62.  
  63. # Set y-axis tick labels
  64. ax.set_yticks(x + (len(group_names) - 1) * bar_width / 2)
  65. ax.set_yticklabels(responses)
  66.  
  67. #Set legend with correct ordering of colors and labels
  68. handles, labels = ax.get_legend_handles_labels()
  69. legend_bbox = bbox_to_anchor=(1.05, 1)
  70.  
  71. #Place the legend outside the plot area
  72. plt.gca().legend(handles[::-1], labels[::-1], title="Groups", loc='upper left', bbox_to_anchor=legend_bbox)
  73. plt.subplots_adjust(right=0.9)  #Adjust the right margin to accommodate the legend
  74.  
  75. #Add the text annotation outside the plot area
  76. plt.gcf().text(0.02, 0.95, textstr, fontsize=14, color='green')
  77.  
  78. #Show the plot
  79. plt.tight_layout()
  80. plt.show()


2. Grouped Bar Charts - 100% Distribution for Each Group

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. import textwrap
  6. from textwrap import wrap
  7. textstr = 'Created at \nwww.tssfl.com'
  8.  
  9. #Create a random dataframe
  10. group_names = np.random.choice(['Group A', 'Group B', 'Group C', 'Group D', 'Group E', 'Group F', 'Group G'], size=100)
  11. responses = np.random.choice(['agree', 'disagree', 'strongly agree', 'strongly disagree'], size=100)
  12. df = pd.DataFrame({'Column1': group_names, 'Column2': responses})
  13.  
  14.  
  15. #Convert dataframe to preserve the original order of responses.
  16. df = pd.crosstab(df['Column1'], df['Column2'])
  17.  
  18. #Convert pandas dataframe to numpy array
  19. data = df.to_numpy()
  20.  
  21. #Calculate the total percentage for each group
  22. group_totals = np.sum(data, axis=1)
  23.  
  24. #Convert the list to a pandas Series
  25. group_series = pd.Series(group_names)
  26. #Extract unique values only - NumPy array
  27. group_names = group_series.unique()
  28.  
  29. response_series = pd.Series(responses)
  30. responses = response_series.unique()
  31.  
  32. #Plot grouped bar charts
  33. fig, ax = plt.subplots(figsize=(14,7))
  34. bar_width = 0.1
  35. opacity = 0.8
  36.  
  37. colors = ['green', 'crimson', '#00FF00', "#FFD700", 'blue', '#4286f4', "#FF4500"]
  38.  
  39. for i, group_data in enumerate(data):
  40.     x = np.arange(len(responses))
  41.     bars = ax.bar(x + i * bar_width, group_data, bar_width,
  42.                   alpha=opacity, color=colors[i], label=group_names[i], align='edge')
  43.  
  44.     #Add percentage annotations for each bar
  45.     for j, bar in enumerate(bars):
  46.         percentage = '{:.2f}%'.format(100 * bar.get_height() / group_totals[i])
  47.         frequency = str(int(bar.get_height()))
  48.         x_pos = bar.get_x() + bar.get_width() / 2
  49.         y_pos = bar.get_height()
  50.         ax.annotate(percentage, (x_pos, y_pos), rotation=90, xytext=(0, 15),
  51.                     textcoords="offset points", ha="center", va="bottom", color='red')
  52.         if y_pos >= 0:
  53.             ax.annotate(frequency, (x_pos, y_pos), rotation=0, xytext=(0, 7),
  54.                         textcoords="offset points", ha="center", va="center", color='green')
  55.  
  56. ax.spines['top'].set_visible(False)
  57. #Set axis labels and title
  58. ax.set_xlabel('Responses')
  59. ax.set_ylabel('Frequency')
  60. ax.set_title('Grouped Bar Charts: Frequency and 100% Distribution for Each Group', size=12, pad=40)
  61.  
  62. #Set x-axis tick labels
  63. ax.set_xticks(x + (len(group_names) - 1) * bar_width / 2)
  64. ax.set_xticklabels(responses)
  65.  
  66. #Wrap column titles for legend, break long column titles after 20 characters for legend titles
  67. #legend_title = "\n".join(textwrap.wrap(df.columns[2], 20))
  68. #legend_title = "\n".join(textwrap.wrap(column2, 30))
  69.  
  70. #Create a legend box outside the plot area
  71. legend = plt.legend(title='Legend', bbox_to_anchor=(1.05, 1), loc='upper left')
  72. plt.subplots_adjust(right=0.9)  #Adjust the right margin to accommodate the legend
  73.  
  74. #Add the text annotation outside the plot area
  75. #plt.figtext(0.1, 0.5, textstr, fontsize=10, verticalalignment='center')
  76. plt.gcf().text(0.02, 0.94, textstr, fontsize=14, color='green')
  77.  
  78. plt.tight_layout()
  79. plt.show()


Horizontal Bar Charts

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. textstr = 'Created at \nwww.tssfl.com'
  5.  
  6. # Create a random dataframe
  7. group_names = np.random.choice(['Group A', 'Group B', 'Group C', 'Group D', 'Group E', 'Group F', 'Group G'], size=100)
  8. responses = np.random.choice(['agree', 'disagree', 'strongly agree', 'strongly disagree'], size=100)
  9. df = pd.DataFrame({'Column1': group_names, 'Column2': responses})
  10.  
  11. #Convert dataframe to preserve the original order of responses.
  12. df = pd.crosstab(df['Column1'], df['Column2'])
  13.  
  14. #Convert pandas dataframe to numpy array
  15. data = df.to_numpy()
  16.  
  17. # Calculate the total percentage for each group
  18. group_totals = np.sum(data, axis=1)
  19.  
  20. #Convert the list to a pandas Series
  21. group_series = pd.Series(group_names)
  22. #Extract unique values only - NumPy array
  23. group_names = group_series.unique()
  24. group_names = group_names[::-1]  #Reverse the order of group labels
  25.  
  26. response_series = pd.Series(responses)
  27. responses = response_series.unique()
  28.  
  29. # Plot grouped bar charts
  30. fig, ax = plt.subplots(figsize=(10, 10))
  31. bar_width = 0.1
  32. opacity = 0.8
  33.  
  34. colors = ['green', 'crimson', '#00FF00', "#FFD700", 'blue', '#4286f4', "#FF4500"]
  35. colors = colors[:len(group_names)][::-1]  # Reverse the order of colors and limit to the number of groups
  36.  
  37. for i, group_data in enumerate(data):
  38.     x = np.arange(len(responses))
  39.     bars = ax.barh(x + i * bar_width, group_data, bar_width,
  40.                    alpha=opacity, color=colors[i], label=group_names[i])
  41.  
  42.     # Add percentage annotations for each bar
  43.     for j, bar in enumerate(bars):
  44.         percentage = '{:.2f}%'.format(100 * bar.get_width() / group_totals[i])
  45.         frequency = str(int(bar.get_width()))
  46.         y_pos = bar.get_y() + bar.get_height() / 2
  47.         x_pos = bar.get_width()
  48.         ax.annotate(percentage, (x_pos, y_pos), xytext=(12, 0),
  49.                     textcoords="offset points", ha="left", va="center", color='red')
  50.        
  51.         if x_pos >= 0:
  52.             ax.annotate(frequency, (x_pos, y_pos), rotation=0, xytext=(6, 0),
  53.                         textcoords="offset points", ha="center", va="center", color='green')
  54.        
  55.  
  56. ax.spines['right'].set_visible(False)
  57. # Set axis labels and title
  58. ax.set_xlabel('Frequency')
  59. ax.set_ylabel('Responses')
  60. ax.set_title('Grouped Bar Charts: Frequency and 100% Distribution for Each Group', size=12, pad=20)
  61.  
  62. # Set y-axis tick labels
  63. ax.set_yticks(x + (len(group_names) - 1) * bar_width / 2)
  64. ax.set_yticklabels(responses)
  65.  
  66. #Set legend with correct ordering of colors and labels
  67. handles, labels = ax.get_legend_handles_labels()
  68. legend_bbox = bbox_to_anchor=(1.05, 1)
  69.  
  70. #Place the legend outside the plot area
  71. plt.gca().legend(handles[::-1], labels[::-1], title="Groups", loc='upper left', bbox_to_anchor=legend_bbox)
  72. plt.subplots_adjust(right=0.9)  #Adjust the right margin to accommodate the legend
  73.  
  74. #Add the text annotation outside the plot area
  75. plt.gcf().text(0.02, 0.95, textstr, fontsize=14, color='green')
  76.  
  77. #Show the plot
  78. plt.tight_layout()
  79. plt.show()


3. Grouped Barcharts - 100% Distribution for Each Response

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. textstr = 'Created at \nwww.tssfl.com'
  5.  
  6. #Create a random dataframe
  7. group_names = np.random.choice(['Group A', 'Group B', 'Group C', 'Group D', 'Group E', 'Group F', 'Group G'], size=100)
  8. responses = np.random.choice(['agree', 'disagree', 'strongly agree', 'strongly disagree'], size=100)
  9. df = pd.DataFrame({'Column1': group_names, 'Column2': responses})
  10.  
  11.  
  12. #Convert dataframe to preserve the original order of responses.
  13. df = pd.crosstab(df['Column1'], df['Column2'])
  14.  
  15. #Convert pandas dataframe to numpy array
  16. data = df.to_numpy()
  17.  
  18. #Calculate the total number for each group
  19. response_totals = np.sum(data, axis=0)
  20. normalized_data = data / response_totals[np.newaxis, :]
  21.  
  22. #Convert the list to a pandas Series
  23. group_series = pd.Series(group_names)
  24. #Extract unique values only - NumPy array
  25. group_names = group_series.unique()
  26.  
  27. response_series = pd.Series(responses)
  28. responses = response_series.unique()
  29.  
  30. #Plot grouped bar charts
  31. fig, ax = plt.subplots(figsize=(14,7))
  32. bar_width = 0.1
  33. opacity = 0.8
  34.  
  35. #colors = ['#4286f4', '#f44174', '#f4d641', '#41f45e']
  36. colors = ['green', 'crimson', '#00FF00', "#FFD700", 'blue', '#4286f4', "#FF4500"]
  37.  
  38. for i, group_data in enumerate(normalized_data):
  39.     x = np.arange(len(responses))
  40.     bars = ax.bar(x + i * bar_width, group_data, bar_width,
  41.                   alpha=opacity, color=colors[i], label=group_names[i], align='edge')
  42.  
  43.     #Add percentage annotations for each bar
  44.     for j, bar in enumerate(bars):
  45.         percentage = '{:.2f}%'.format(100 * bar.get_height())
  46.         frequency = str(int(response_totals[j]*bar.get_height()))
  47.         x_pos = bar.get_x() + bar.get_width() / 2
  48.         y_pos = bar.get_height()
  49.         ax.annotate(percentage, (x_pos, y_pos), rotation=90, xytext=(0, 15),
  50.                     textcoords="offset points", ha="center", va="bottom", color='red')
  51.        
  52.         if y_pos >= 0:
  53.             ax.annotate(frequency, (x_pos, y_pos), rotation=0, xytext=(0, 7),
  54.                         textcoords="offset points", ha="center", va="center", color='blue')
  55.  
  56. ax.spines['top'].set_visible(False)
  57. #Set axis labels and title
  58. ax.set_xlabel('responses')
  59. ax.set_ylabel('Fraction')
  60. ax.set_title('Grouped Bar Charts: 100% Distribution for Each Response', size=12, pad=40)
  61.  
  62. #Set x-axis tick labels
  63. ax.set_xticks(x + (len(group_names) - 1) * bar_width / 2)
  64. ax.set_xticklabels(responses)
  65.  
  66. #Create a legend box outside the plot area
  67. legend = plt.legend(title='Groups', bbox_to_anchor=(1.05, 1), loc='upper left')
  68. plt.subplots_adjust(right=0.9)  #Adjust the right margin to accommodate the legend
  69.  
  70. #Add the text annotation outside the plot area
  71. plt.gcf().text(0.02, 0.94, textstr, fontsize=14, color='green')
  72.  
  73. #Show the plot
  74. plt.tight_layout()
  75. plt.show()


Horizontal Bar Charts Version

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. textstr = 'Created at \nwww.tssfl.com'
  5.  
  6. #Create a random dataframe
  7. group_names = np.random.choice(['Group A', 'Group B', 'Group C', 'Group D', 'Group E', 'Group F', 'Group G'], size=100)
  8. responses = np.random.choice(['agree', 'disagree', 'strongly agree', 'strongly disagree'], size=100)
  9. df = pd.DataFrame({'Column1': group_names, 'Column2': responses})
  10.  
  11. #Convert dataframe to preserve the original order of responses.
  12. df = pd.crosstab(df['Column1'], df['Column2'])
  13.  
  14. #Convert pandas dataframe to numpy array
  15. data = df.to_numpy()
  16.  
  17. #Calculate the total number for each response
  18. response_totals = np.sum(data, axis=0)
  19. normalized_data = data / response_totals[np.newaxis, :]
  20.  
  21. #Convert the list to a pandas Series
  22. group_series = pd.Series(group_names)
  23. #Extract unique values only - NumPy array
  24. group_names = group_series.unique()
  25.  
  26. response_series = pd.Series(responses)
  27. responses = response_series.unique()
  28.  
  29. #Plot grouped bar charts
  30. fig, ax = plt.subplots(figsize=(10, 10))
  31. bar_width = 0.1
  32. opacity = 0.8
  33.  
  34. colors = ['green', 'crimson', '#00FF00', "#FFD700", 'blue', '#4286f4', "#FF4500"]
  35. colors = colors[:len(group_names)][::-1]  # Reverse the order of colors and limit to the number of groups
  36.  
  37. for i, group_data in enumerate(normalized_data):
  38.     x = np.arange(len(responses))
  39.     bars = ax.barh(x + i * bar_width, group_data, bar_width,
  40.                    alpha=opacity, color=colors[i], label=group_names[i])
  41.  
  42.     # Add percentage annotations for each bar
  43.     for j, bar in enumerate(bars):
  44.         percentage = '{:.2f}%'.format(100 * bar.get_width())
  45.         frequency = str(int(response_totals[j]*bar.get_width()))
  46.         y_pos = bar.get_y() + bar.get_height() / 2
  47.         x_pos = bar.get_width()
  48.         ax.annotate(percentage, (x_pos, y_pos), xytext=(12, 0),
  49.                     textcoords="offset points", ha="left", va="center", color='red')
  50.        
  51.         if y_pos >= 0:
  52.             ax.annotate(frequency, (x_pos, y_pos), rotation=0, xytext=(6, 0),
  53.                         textcoords="offset points", ha="center", va="center", color='blue')
  54.            
  55. ax.spines['right'].set_visible(False)
  56. #Set axis labels and title
  57. ax.set_xlabel('Fraction (Out of 1)')
  58. ax.set_ylabel('Responses')
  59. ax.set_title('Grouped Bar Charts: 100% Distribution for Each Response', size=12, pad=30)
  60.  
  61. # Set y-axis tick labels
  62. ax.set_yticks(x + (len(group_names) - 1) * bar_width / 2)
  63. ax.set_yticklabels(responses)
  64.  
  65. #Set legend with correct ordering of colors and labels
  66. handles, labels = ax.get_legend_handles_labels()
  67. legend_bbox = bbox_to_anchor=(1.05, 1)
  68.  
  69. #Place the legend outside the plot area
  70. plt.gca().legend(reversed(handles), reversed(labels), title="Groups", loc='upper left', bbox_to_anchor=legend_bbox)
  71. plt.subplots_adjust(right=0.9)  #Adjust the right margin to accommodate the legend
  72.  
  73. #Add the text annotation outside the plot area
  74. plt.gcf().text(0.02, 0.95, textstr, fontsize=14, color='green')
  75.  
  76. #Show the plot
  77. plt.tight_layout()
  78. plt.show()

0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
User avatar
Eli
Senior Expert Member
Reactions: 183
Posts: 5334
Joined: 9 years ago
Location: Tanzania
Has thanked: 75 times
Been thanked: 88 times
Contact:

#22

Stacked Bar Charts

Chart 1

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. #Randomized string values for column1
  6. column1_values = np.random.choice(['agree', 'disagree', 'strongly agree', 'strongly disagree'], size=100)
  7.  
  8. #Randomized string values for column2
  9. column2_values = np.random.choice(['Group A', 'Group B', 'Group C', 'Group D', 'Group E', 'Group F', 'Group G'], size=100)
  10.  
  11. #Create the DataFrame
  12. df = pd.DataFrame({'Column1': column1_values, 'Column2': column2_values})
  13.  
  14. #Calculate the percentage distribution for each group
  15. grouped_counts = df.groupby(['Column2', 'Column1']).size()
  16. grouped_percentages = grouped_counts.groupby(level=0).apply(lambda x: 100 * x / x.sum())
  17.  
  18. #Reshape the DataFrame for plotting
  19. grouped_percentages = grouped_percentages.unstack()
  20.  
  21.  
  22. #Plotting the grouped bar charts
  23. fig, ax = plt.subplots(figsize=(10, 6))
  24. ax = grouped_percentages.plot(kind='bar', stacked=True, ax=ax)
  25.  
  26. #Set the plot labels and title
  27. plt.xlabel('Column2')
  28. plt.ylabel('Percentage')
  29. plt.title('Grouped Bar Charts')
  30.  
  31. #Add percentage labels on top of each bar
  32. for p in ax.patches:
  33.     width = p.get_width()
  34.     height = p.get_height()
  35.     x, y = p.get_xy()
  36.     ax.text(x + width/2, y + height/2, '{:.1f}%'.format(height), ha='center')
  37.  
  38. #Modify x-axis labels
  39. x_labels = [label.get_text().split(',')[0].replace('(', '').strip() for label in ax.get_xticklabels()]
  40. ax.set_xticklabels(x_labels)
  41.  
  42. #Move the legend outside the plot
  43. lgd = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
  44.  
  45. #Display the plot
  46. plt.tight_layout()
  47. plt.show()


Chart 2

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4. #Create data
  5. data = np.array([[35, 25, 25, 15],
  6.               [20, 30, 30, 20],
  7.               [30, 20, 25, 25],
  8.                 [40, 50, 60, 70]])
  9.  
  10. #Create the stacked percentage bar chart
  11. fig, ax = plt.subplots()
  12. ax.stackplot(np.arange(4), data, labels=['A', 'B', 'C', 'D'])
  13.  
  14. #Increase the width and size of the plot
  15. fig.set_size_inches(10, 6)
  16. ax.set_xlabel('Type', fontsize=14)
  17. ax.set_ylabel('Count', fontsize=14)
  18. ax.set_title('Stacked Bar Chart', fontsize=16)
  19. ax.legend(fontsize=12)
  20.  
  21. #Move the legend outside the plot
  22. lgd = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
  23. #Show the plot
  24. plt.tight_layout()
  25. plt.show()

0
TSSFL -- A Creative Journey Towards Infinite Possibilities!
Post Reply

Return to “Technologies for Teaching, Learning, Research, Problem Solving and Business”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 13 guests