2017-04-01 106 views
1

我有一个这样的数据集:分组线图

DataSet image

DataSet可以在这里找到:https://ucr.fbi.gov/crime-in-the-u.s/2013/crime-in-the-u.s.-2013/tables/1tabledatadecoverviewpdf/table_1_crime_in_the_united_states_by_volume_and_rate_per_100000_inhabitants_1994-2013.xls

,我想绘制包含线线图的每一个犯罪率按年份。 类似这样的: Crime Rate graph
但该图显示了像2005.5 2007.5这样的x轴连续年。 任何人都可以提供帮助吗?或者提出一个更好的方法来做到这一点。由于

这里是代码:

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

cd =pd.read_clipboard() #after copying the dataset from given url above 


     yearRate = cd[['Year','ViolentCrimeRate','MurderRate','RapeRate','RobberyRate','AggravatedAssaultRate','PropertyCrimeRate','BurglaryRate','LarcenyTheftRate','MotorVehicleTheftRate']] 
    # These are the "Tableau 20" colors as RGB.  
    tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),  
       (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),  
       (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),  
       (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),  
       (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] 
    for i in range(len(tableau20)):  
     r, g, b = tableau20[i]  
     tableau20[i] = (r/255., g/255., b/255.) 


    plt.figure(figsize=(20,15)) 
    ax = plt.subplot(111) 

    ax.spines['top'].set_visible(False) 
    ax.spines['bottom'].set_visible(False) 
    ax.spines['left'].set_visible(False) 
    ax.spines['right'].set_visible(False) 

    plt.ylim(0,5000) 
    plt.xlim(1994, 2013) 

    plt.yticks(fontsize=14) 
    plt.xticks(fontsize=14) 

    for y in range(0, 5000, 1000):  
     plt.plot(range(1994, 2013), [y] * len(range(1994, 2013)), "--", lw=0.5, color="black", alpha=0) 

    rates=['ViolentCrimeRate','MurderRate','RapeRate','RobberyRate','AggravatedAssaultRate','PropertyCrimeRate','BurglaryRate','LarcenyTheftRate','MotorVehicleTheftRate'] 

    for rank, column in enumerate(rates):  
     # Plot each line separately with its own color, using the Tableau 20  
     # color set in order.  
     plt.plot(yearRate.Year.values,yearRate[column.replace("\n", " ")].values,lw=2.5, color=tableau20[rank])  
     # Add a text label to the right end of every line. Most of the code below  
     # is adding specific offsets y position because some labels overlapped.  
     y_pos = yearRate[column.replace("\n", " ")].values[-1] - 0.5  
     if column == "MotorVehicleTheftRate":  
      y_pos -= 50 
     elif column == "MurderRate":  
      y_pos -= 50 
     plt.text(2013, y_pos, column, fontsize=14, color=tableau20[rank]) 
+1

你能举一个最简单的例子吗?特别是有一些可复制的代码会很好。 –

+0

@ArcoBast 你想让我粘贴这里的代码或数据集? –

+0

您可以在原始文章中编辑它,以便我可以复制并粘贴代码并立即运行? –

回答

0

添加:

plt.xticks(cd['Year']) 

解决的问题。