python - 如何在绘图的 x 轴上添加年份?
问题描述
我的代码如下:
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 轴上添加 Years 2004,2009,2014,2019?我想要投票百分比与年份图。在使用代码时,我无法在 x 轴上绘制年份。
解决方案
我已经评论了我添加输入的所有行。我希望这就是你要找的。
选项 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();
输出如下:
推荐阅读
- database - Google Cloud Sql - 突然更改了它的 IP,关闭了备份,我的所有数据都丢失了。(旧状态自动恢复)
- php - 为什么网站图标不显示?
- angular - 角度检测双击或点击事件
- javascript - 如何使用 WebRTC - Laravel 在视频会议中录制本地和远程流?
- asp.net - 如何在.net core 2.0中获取用户使用的浏览器名称
- spring - Spring EL File.renameTo 不适用于已安装的目录
- jquery - 在服务器端数据源中隐藏和显示数据表
- java - Mysql 与 springboot 应用程序部署在 Docker windows 桌面错误
- java - 如何更改使用 Spring 创建的 bean 上的一个参数
- r - dplyr.snowflakedb 是否仅与 32 位 JDK 一起运行?