我觉得自己很笨,但似乎无法使线形图与Seaborn一起正常工作。似乎与x轴有关,但我不明白。
我的源数据是来自https://www.insee.fr/fr/statistiques/2540004的原始文件。 ch3在seaborn之前看起来像这样:
annais dpt nombre
18 1952 23 3
23 1956 23 3
29 1961 23 4
31 1962 23 4
33 1963 23 8
35 1964 23 12
37 1965 23 16
39 1966 23 26
41 1967 23 37
43 1968 23 35
47 1969 23 58
51 1970 23 64
55 1971 23 39
59 1972 23 42
63 1973 23 48
67 1974 23 32
71 1975 23 27
75 1976 23 21
79 1977 23 17
83 1978 23 23
87 1979 23 15
91 1980 23 18
95 1981 23 14
99 1982 23 9
103 1983 23 8
107 1984 23 11
111 1985 23 3
115 1986 23 7
119 1987 23 5
129 1990 23 4
.. ... .. ...
98 1981 93 208
102 1982 93 209
106 1983 93 162
110 1984 93 180
114 1985 93 136
118 1986 93 126
122 1987 93 112
125 1988 93 100
128 1989 93 64
132 1990 93 61
135 1991 93 71
138 1992 93 56
141 1993 93 40
144 1994 93 54
147 1995 93 42
150 1996 93 30
153 1997 93 17
156 1998 93 21
159 1999 93 14
162 2000 93 17
165 2001 93 28
168 2002 93 16
171 2003 93 10
174 2004 93 11
177 2005 93 4
180 2006 93 4
184 2008 93 5
187 2009 93 4
191 2011 93 4
198 2017 93 4
[199 rows x 3 columns]
基本上尝试按年份(x轴)绘制姓氏(y轴)的频率为4个部门。 年(“ annais”)是一个四位数的整数。为了安全起见,我对值进行了排序。 但是,折线图一直在中断,值不能从右到左连续保持不变。 Pandas plot()需要一个特殊的枢轴,但至少它可以工作。 有什么想法吗?
有效的代码(熊猫Plots()):
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
%matplotlib inline
plt.rcParams['figure.figsize'] = [12, 8]
import pandas as pd
import seaborn as sns
df = pd.read_csv('dpt2017.txt', sep = '\t')
##df = pd.read_csv('nat2017.txt', sep = '\t')
ch = df.loc[df['preusuel'].isin(['CHRISTOPHE'])]
ch = ch[ch.annais != 'XXXX']
ch.nombre.astype(int)
ch.annais.astype(int)
ch = ch.drop(columns=['sexe'])
ch = ch[ch.dpt.isin(['75', '92', '93', '23'])]
ch2=ch.groupby(['preusuel', 'annais', 'dpt']).sum()
ch3=ch2.reset_index()
ch3 = ch3.sort_values(by=['dpt','annais']).drop(columns=['preusuel'])
graph = ch3.pivot(index='annais', columns='dpt', values='nombre')
graph.plot()
可破解的代码(Seaborn):
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
%matplotlib inline
plt.rcParams['figure.figsize'] = [12, 8]
import pandas as pd
import seaborn as sns
sns.set(style="darkgrid")
df = pd.read_csv('dpt2017.txt', sep = '\t')
##df = pd.read_csv('nat2017.txt', sep = '\t')
ch = df.loc[df['preusuel'].isin(['CHRISTOPHE'])]
ch = ch[ch.annais != 'XXXX']
ch.nombre.astype(int)
ch.annais.astype(int)
ch.annais.astype(int)
ch = ch.drop(columns=['sexe'])
ch = ch[ch.dpt.isin(['75', '92', '93', '23'])]
ch2=ch.groupby(['preusuel', 'annais', 'dpt']).sum()
ch3=ch2.reset_index()
ch3 = ch3.sort_values(by=['dpt','annais']).drop(columns=['preusuel'])
palette = sns.color_palette('muted',4)
ax = sns.lineplot(x="annais", y="nombre", hue = "dpt",palette=palette, data=ch3)
ax.xaxis.set_major_locator(plt.MaxNLocator(10))
ax.yaxis.set_major_locator(plt.MaxNLocator(10))
答案 0 :(得分:0)
虽然这不能解释为什么seaborn担心'annais'字段为str的年份,并将其强制转换为int起作用。
我以前曾尝试这样做,但是您必须使用ch['annais']=ch.annais.astype(int)
而不是ch.annais.astype(int)
!
非常感谢@tobsecret和@ImportanceOfBeingErnest