【问题标题】:How to add Years on x-axis in plot?如何在绘图的 x 轴上添加年份?
【发布时间】:2020-02-04 08:08:49
【问题描述】:

New Plot

我的代码如下:

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()

我是 Python 和数据科学的新手。我应该如何在图表的 x 轴上添加年份 2004,2009,2014,2019?我想要投票百分比与年份图。在使用代码时,我无法在 x 轴上绘制年份。

【问题讨论】:

  • 您可以发布指向数据集或 csv 文件的链接吗?
  • 如何在条形图中的条形顶部添加值,请查看stack overflow post
  • 在这里看不到任何发布 csv 数据集的方法。 @instinct246
  • @TalhaAnwar 我之前也看到了,但不知道应该如何更改我的代码?
  • 你能把这个“encoded_data.sample().to_dict()”的o/p贴出来吗?我会更容易复制和帮助。我假设 encoded_data 是您用于绘图的数据集。

标签: python python-3.x machine-learning data-visualization data-science


【解决方案1】:

我已经评论了我添加输入的所有行。我希望这就是你要找的。​​p>

选项 1(线图):

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();

如下所示:

选项 2(条形图 + 线):

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();

输出如下:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 2019-02-19
    • 2021-09-30
    相关资源
    最近更新 更多