[英]How to plot seaborn lineplot with string variables on x-axis
我正在嘗試使用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 lineplot 在 x 軸上繪制字符串值。?
是可以的,但是你需要給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 將無法檢測到這一點。
根據seaborn 文檔lineplot 不支持非數字數據。
不完全清楚您想要實現什么,但是我想您正在尋找的是seaborn 散點圖函數,並且您必須提供要繪制的 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)
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.