Monday, July 31, 2017

Python Matplotlib and Group Horizontal Bar Chart


Importing Data download data here
  1. import numpy as np  
  2. import pandas as pd  
  3. import matplotlib.pyplot as plt  
  4.   
  5. #Importing Data download data here  
  6. df = pd.read_csv(r'F:\Python\Country_Population_Year.txt', sep='\t',   
  7.                  low_memory=True, encoding='utf-8', error_bad_lines=False, thousands=',', header=0)  
  8.   
  9. df.set_index('Country or Territory', inplace=True)  
  10. #display first n countries....  
  11. n = 20  
  12.   
  13. #set y points and y labels.....  
  14. y_pos = [i for i in range(n)]  
  15. y_label = [i for i in df.index.tolist()[0:n]] #first 20 countries  
  16. width = 0.85  
  17.   
  18. fig = plt.figure(figsize=(15,7), dpi=70)  
  19. plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.05, hspace=None)  
  20.   
  21. ax0 = fig.add_subplot(311)  
  22. plt.title("Population by Country: Top 20 Country ('000)")  
  23. ax0.spines['left'].set_visible(False)  
  24. ax0.spines['right'].set_visible(False)  
  25. ax0.spines['top'].set_visible(False)  
  26. ax0.spines['bottom'].set_visible(False)  
  27.   
  28. ax0.axes.get_xaxis().set_visible(False)  
  29. ax0.axes.get_yaxis().set_visible(False)  
  30.   
  31. ax0.set_yticks([1])  
  32. ax0.set_yticklabels([''], fontsize=0)  
  33.   
  34. ax1 = fig.add_subplot(131)  
  35. ax2 = fig.add_subplot(132)  
  36. ax3 = fig.add_subplot(133)  
  37.   
  38. ax1.spines['right'].set_visible(False)  
  39. ax1.spines['top'].set_visible(False)  
  40. ax1.spines['bottom'].set_visible(False)  
  41.   
  42. ax2.spines['left'].set_visible(False)  
  43. ax2.spines['right'].set_visible(False)  
  44. ax2.spines['top'].set_visible(False)  
  45. ax2.spines['bottom'].set_visible(False)  
  46.   
  47. ax3.spines['left'].set_visible(False)  
  48. ax3.spines['right'].set_visible(False)  
  49. ax3.spines['top'].set_visible(False)  
  50. ax3.spines['bottom'].set_visible(False)  
  51.   
  52. ax1.xaxis.grid(b=False, which='major', color='gray', linestyle='--')  
  53. ax2.xaxis.grid(b=False, which='major', color='gray', linestyle='--')  
  54. ax3.xaxis.grid(b=False, which='major', color='gray', linestyle='--')  
  55.   
  56. hbar1 = ax1.barh(y_pos, (df['1950']/1000).tolist()[0:n], width, align='center',   
  57.                color='#5291A2', ecolor='black',  
  58.                label='Year 1950')  
  59.   
  60.   
  61. hbar2 = ax2.barh(y_pos, (df['1955']/1000).tolist()[0:n], width, align='center',   
  62.                color='#8F26EC', ecolor='black',  
  63.                label='Year 1955')  
  64.   
  65. hbar3 = ax3.barh(y_pos, (df['1960']/1000).tolist()[0:n], width, align='center',   
  66.                color='#6482B4', ecolor='black',  
  67.                label='Year 1960')  
  68.   
  69. ax1.set_yticks(y_pos)  
  70. ax2.set_yticks(y_pos)  
  71. ax3.set_yticks(y_pos)  
  72.   
  73. ax1.set_yticklabels(y_label, fontsize=10)  
  74. ax2.set_yticklabels(['']*n, fontsize=10)  
  75. ax3.set_yticklabels(['']*n, fontsize=10)  
  76.   
  77. ax1.invert_yaxis()  # labels read top-to-bottom  
  78. ax2.invert_yaxis()  # labels read top-to-bottom  
  79. ax3.invert_yaxis()  # labels read top-to-bottom  
  80.   
  81. ax1.set_xlabel("Population ('000)")  
  82. ax2.set_xlabel("Population ('000)")  
  83. ax3.set_xlabel("Population ('000)")  
  84.   
  85. ax1.legend(loc='lower left')  
  86. ax2.legend(loc='lower left')  
  87. ax3.legend(loc='lower left')  
  88.   
  89. plt.show()  















Let's have an automated way to plot all the Years in a single plot.

  1. import numpy as np  
  2. import pandas as pd  
  3. import matplotlib.pyplot as plt  
  4. import random  
  5.   
  6. #Importing Data  
  7. df = pd.read_csv(r'F:\Python\Country_Population_Year.txt', sep='\t',   
  8.                  low_memory=True, encoding='utf-8', error_bad_lines=False, thousands=',', header=0)  
  9.   
  10. df.set_index('Country or Territory', inplace=True)  
  11. #display first n countries....  
  12. n = 20  
  13. #Calculate total Years (columns)  
  14. Year_N = len(df.columns)  
  15.   
  16. #set y points and y labels.....  
  17. y_pos = [i for i in range(n)]  
  18. y_label = [i for i in df.index.tolist()[0:n]] #first 20 countries  
  19. width = 0.9  
  20.   
  21. fig = plt.figure(figsize=(50,7), dpi=100)  
  22. plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)  
  23.   
  24. ax0 = fig.add_subplot(211)  
  25. plt.title("Population by Country: Top 20 Country ('000)", fontsize=20)  
  26.   
  27.   
  28. ax0.spines['left'].set_visible(False)  
  29. ax0.spines['right'].set_visible(False)  
  30. ax0.spines['top'].set_visible(False)  
  31. ax0.spines['bottom'].set_visible(False)  
  32.   
  33. ax0.axes.get_xaxis().set_visible(False)  
  34. ax0.axes.get_yaxis().set_visible(False)  
  35.   
  36. ax0.set_yticks([1])  
  37. ax0.set_yticklabels([''], fontsize=0)  
  38.   
  39. color=[]  
  40. for i in range(Year_N):  
  41.     r = lambda: random.randint(0,255)  
  42.     color.append('#%02X%02X%02X' % (r(),r(),r()))  
  43.   
  44. for i in range(Year_N):  
  45.     ax = fig.add_subplot(1,Year_N,i+1)  
  46.     if i == 0:  
  47.         ax.spines['right'].set_visible(False)  
  48.         ax.spines['top'].set_visible(False)  
  49.         ax.spines['bottom'].set_visible(False)  
  50.     else:  
  51.         ax.spines['left'].set_visible(False)  
  52.         ax.spines['right'].set_visible(False)  
  53.         ax.spines['top'].set_visible(False)  
  54.         ax.spines['bottom'].set_visible(False)  
  55.     ax.xaxis.grid(b=False, which='major', color='gray', linestyle='--')  
  56.     hbar = ax.barh(y_pos, (df[str(df.columns.tolist()[i])]/1000).tolist()[0:n], width,   
  57.                    align='center', color=color[i], ecolor='black', label='Year: '+str(df.columns.tolist()[i]))  
  58.       
  59.     ax.set_yticks(y_pos)  
  60.     if i == 0:  
  61.         ax.set_yticklabels(y_label, fontsize=10)  
  62.     else:  
  63.         ax.set_yticklabels(['']*n, fontsize=10)  
  64.       
  65.     ax.invert_yaxis()  # labels read top-to-bottom  
  66.     ax.set_xlabel("Population ('000)")  
  67.     ax.legend(loc='lower left')  
  68.       
  69. plt.show()