我正在尝试使用seaborn.lineplot()
在x轴上带有字符串变量的时间序列图。
我的数据如下:
month_year billamount tips
0 2018-03 200 10
1 2018-04 230 12
2 2018-05 500 10
3 2018-06 300 15
4 2018-07 200 20
5 2018-08 150 5
6 2018-09 100 5
7 2018-10 400 5
8 2018-11 500 10
9 2018-12 250 30
10 2019-01 200 20
在上表中,month_year
是对象类型(字符串)
尝试绘制时,它显示错误消息:
ValueError: A wide-form input must have only numeric values.
是否可以使用seaborn线图在x轴上绘制字符串值?
答案 0 :(得分:1)
根据seaborn documentation线图,不支持非数字数据。
目前尚不清楚要实现什么,但是我想您要寻找的是seaborn scatterplot function,并且必须提供要绘制的x和y变量的名称。
示例:
tips = [10, 12,10,15]
billamount = [200, 230, 500, 300]
month_year= ["2018-03", "2018-04", "2018-05", "2018-06", ]
data = pd.DataFrame(np.array([tips, billamount, month_year]).T,
columns=["tips", "billamount", "month_year"])
ax = sns.scatterplot(x="month_year", y="billamount", data=data)
答案 1 :(得分:1)
我不确定seaborn是否真的应该在线图中使用字符串。但您始终可以选择使用普通的matplotlib plot
。
import matplotlib.pyplot as plt
import pandas as pd
data = pd.DataFrame({"billamount" : [200, 230, 500, 300],
"month_year" : ["2018-03", "2018-04", "2018-05", "2018-06", ]})
plt.plot("month_year", "billamount", data=data)
plt.show()
答案 2 :(得分:0)
有可能,但是您需要为seaborn提供更多指导:
import io
import pandas as pd
raw_data = """ month_year billamount tips
0 2018-03 200 10
1 2018-04 230 12
2 2018-05 500 10
3 2018-06 300 15
4 2018-07 200 20
5 2018-08 150 5
6 2018-09 100 5
7 2018-10 400 5
8 2018-11 500 10
9 2018-12 250 30
10 2019-01 200 20"""
df = pd.read_csv(io.StringIO(raw_data), sep='\s+')
sns.lineplot(x='month_year', y='billamount', data=df)
当然,如果字符串表示的值间隔不均匀(即,如果您在某个地方跳过了一个月),seaborn将无法检测到。
答案 3 :(得分:0)
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
import numpy as np
import csv
f=np.genfromtxt('Data.txt',dtype=float,skip_header=1) #Data.txt is your data
month_year=f[:,0]
billamount=f[:,1]
tips=f[:2]
data=pd.DataFrame({'month_year':month_year,'billamount':bill_amount, 'tips':tips})
data.to_csv('Data.csv') # it will save the csv file
plt.figure(figsize=(8,14))
sns.lineplot(x=data['month_year'],y=data['tips'])
plt.title('seasonality of tips')
plt.xlabel('Years and Month')
plt.ylabel('Tips')
plt.show()