0

New Plot

My code is as follows:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

data=pd.read_csv("C:/Users/Jagdeep/Downloads/Alokji political data/political plot data parliamentary.csv")

fig=plt.figure()
ax = fig.add_subplot(111)
plt.plot(parl_data['BJP'], marker='o', label='BJP', color='red')
plt.plot(parl_data['INC'], marker='o', label='INC', color='blue')
plt.plot(parl_data['AAP'], marker='o', label='AAP', color='brown')
plt.plot(parl_data['Total_Polling'], marker='o', label='Total 
Polling', color='green', linestyle='dashed')
plt.legend()

for i,j in parl_data.BJP.items():
    ax.annotate(str(j), xy=(i, j))
for i,j in parl_data.INC.items():
    ax.annotate(str(j), xy=(i, j))
for i,j in parl_data.AAP.items():
    ax.annotate(str(j), xy=(i, j))
for i,j in parl_data.Total_Polling.items():
    ax.annotate(str(j), xy=(i, j))


ax.set_alpha(0.8)
ax.set_title("Party-wise vote share in Lok Sabha Polls (Delhi) 2019", 
fontsize=15)
ax.set_ylabel("Parliament Polling Percentage", fontsize=15);
ax.set_xlabel("Election Year", fontsize=15)

ax.set_xticklabels(['2004','2009','2014','2019'])
plt.yticks(np.arange(0,100,10))

plt.show()

I am a new to Python and data science. How should I add Years 2004,2009,2014,2019 on x axis in the graph? I want Polling % vs Years plot. On using the code, I am not able to plot years on x-axis.

  • possible for you to post a link to the data set or the csv file ? – instinct246 Feb 04 '20 at 08:26
  • How to add value on top of bar in bar plot, check this [stack overflow post](https://stackoverflow.com/questions/30228069/how-to-display-the-value-of-the-bar-on-each-bar-with-pyplot-barh) – Talha Anwar Feb 04 '20 at 08:30
  • Cannot see any way here to post csv dataset. @instinct246 – Jagdeep Singh Feb 04 '20 at 10:14
  • @TalhaAnwar I saw that earlier too but unable to figure out how should I change my code? – Jagdeep Singh Feb 04 '20 at 10:16
  • Can you post the o/p of this "encoded_data.sample().to_dict()" ? will be easier for me to reproduce and help. I assume encoded_data is the data set you are using to plot. – instinct246 Feb 04 '20 at 10:28
  • Please edit the original post with the data (i:e - the output of "encoded_data.sample().to_dict()" ) and the code (which you have posted). It will be more readable that way. I can also take the dictionary to make the data frame and then plot. – instinct246 Feb 04 '20 at 17:45
  • I have tweaked the code and the question bro .. kindly help me out .. tried a different approach of using line plot instead @instinct246 – Jagdeep Singh Feb 04 '20 at 17:50
  • Looks like you are in right direction. But for me to be able to try the plot and help, i need the data points. If you are trying to plot the data contained in parl_data dataframe - can you post the o/p of parl_data.to_dict() in the post. It may be a long dictionary - but thats ok – instinct246 Feb 04 '20 at 17:56
  • {'Year': {0: 2004, 1: 2009, 2: 2014, 3: 2019}, 'BJP': {0: 40.67, 1: 35.2, 2: 46.63, 3: 56.56}, 'INC': {0: 54.81, 1: 57.11, 2: 15.22, 3: 22.63}, 'AAP': {0: 0.0, 1: 0.0, 2: 33.08, 3: 18.2}, 'Total_Polling': {0: 47.09, 1: 51.81, 2: 65.1, 3: 60.59}} @instinct246 – Jagdeep Singh Feb 04 '20 at 18:16
  • @Jagdeep I have added primarily 2 lines to resolve your problem. Rest are just cosmetic changes. You may keep or get rid of them. You may modify further to make the numbers look less cluttered...as you need. Please 'accept' the answer if that resolves your problem. :) – instinct246 Feb 04 '20 at 18:51

1 Answers1

1

I have commented all the lines where I added my input. I hope this is what you were looking for.

Option 1 (Line plot):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from  matplotlib.ticker import MaxNLocator #imported this to set the tick locators correct
import seaborn as sns
%matplotlib inline

dic = {'Year': {0: 2004, 1: 2009, 2: 2014, 3: 2019}, 'BJP': {0: 40.67, 1: 35.2, 2: 46.63, 3: 56.56}, 'INC': {0: 54.81, 1: 57.11, 2: 15.22, 3: 22.63}, 'AAP': {0: 0.0, 1: 0.0, 2: 33.08, 3: 18.2}, 'Total_Polling': {0: 47.09, 1: 51.81, 2: 65.1, 3: 60.59}} 
parl_data = pd.DataFrame(dic)

fig, ax = plt.subplots(figsize = (15,6)) # assigned fig and ax in one line and added size to figure for better visibility
plt.plot(parl_data['BJP'], marker='o', label='BJP', color='red')
plt.plot(parl_data['INC'], marker='o', label='INC', color='blue')
plt.plot(parl_data['AAP'], marker='o', label='AAP', color='brown')
plt.plot(parl_data['Total_Polling'], marker='o', label='Total Polling', color='green', linestyle='dashed')
plt.legend()

for i,j in parl_data.BJP.items():
    ax.annotate(str(j), xy=(i, j), size = 15) # increased the font size as it was looking cluttered
for i,j in parl_data.INC.items():
    ax.annotate(str(j), xy=(i, j), size = 15) # increased the font size as it was looking cluttered
for i,j in parl_data.AAP.items():
    ax.annotate(str(j), xy=(i, j), size = 15) # increased the font size as it was looking cluttered
for i,j in parl_data.Total_Polling.items():
    ax.annotate(str(j), xy=(i, j), size = 15) # increased the font size as it was looking cluttered


ax.set_alpha(0.8)
ax.set_title("\n\nParty-wise vote share in Lok Sabha Polls (Delhi) 2019\n", fontsize=15)
ax.set_ylabel("Parliament Polling Percentage\n", fontsize=15);
ax.set_xlabel("Election Year\n", fontsize=15)
plt.yticks(np.arange(0,100,10))

##I Added from here
ax.xaxis.set_major_locator(MaxNLocator(4)) # To set the locators correct
ax.set_xticklabels(['0','2004','2009','2014','2019']) # To set the labels correct.

plt.tick_params( left = False,bottom = False, labelsize= 13) #removed tick lines
plt.legend(frameon = False, loc = "best", ncol=4, fontsize = 14) # removed the frame around the legend and spread them along a line
plt.box(False) # Removed the box - 4 lines - you may keep if you like. Comment this line out
plt.style.use('bmh') #used the style bmh for better look n feel (my view) you may remove or keep as you like


plt.show();

It looks as below: enter image description here

Option 2 (Bar plot + line):

width = .35
ind = np.arange(len(parl_data))

fig, ax = plt.subplots(figsize = (15,6)) # assigned fig and ax in one line and added size to figure for better visibility

#plot bars for bjp,inc & aap
bjp = plt.bar(ind,parl_data['BJP'],width/2, label='BJP', color='red')
inc = plt.bar(ind+width/2,parl_data['INC'],width/2, label='INC', color='green')
aap = plt.bar(ind+width,parl_data['AAP'],width/2, label='AAP', color='orange')

#Make a line plot for Total_Polling
plt.plot(parl_data['Total_Polling'],'bo-',label='Total Polling', color = 'darkred')

def anotate_bars(bars):
    '''
    This function helps annotate the bars with data labels in the desired position.
    '''
    for bar in bars:
        h = bar.get_height()
        ax.text(bar.get_x()+bar.get_width()/2., 0.75*h, h,ha='center', va='bottom', color = 'white', fontweight='bold')

anotate_bars(bjp)
anotate_bars(inc)
anotate_bars(aap)

for x,y in parl_data['Total_Polling'].items():
    ax.text(x, y+4, y,ha='center', va='bottom', color = 'black', fontweight='bold')


ax.set_title("\n\nParty-wise vote share in Lok Sabha Polls (Delhi) 2019\n", fontsize=15)
ax.set_ylabel("Parliament Polling Percentage\n", fontsize=15);
ax.set_xlabel("Election Year\n", fontsize=15)
plt.yticks(np.arange(0,100,10))

ax.xaxis.set_major_locator(MaxNLocator(4)) # To set the locators correct
ax.set_xticklabels(['0','2004','2009','2014','2019']) # To set the labels correct.

plt.tick_params( left = False,bottom = False, labelsize= 13) #removed tick lines
plt.legend(frameon = False, loc = "best", ncol=4, fontsize = 14) # removed the frame around the legend and spread them along a line
plt.style.use('bmh') #used the style bmh for better look n feel (my view) you may remove or keep as you like


plt.show();

Output is as below:

enter image description here

instinct246
  • 960
  • 9
  • 15