[英]Plot multiple lines from dataframe
I have the following table:我有下表:
Time![]() |
Type![]() |
Usage1 [%]![]() |
Usage2 [%]![]() |
---|---|---|---|
2021-07-09 09:00 DST ![]() |
LG1 ![]() |
60.0581 ![]() |
87.4926 ![]() |
2021-07-09 09:00 DST ![]() |
LG2 ![]() |
42.1409 ![]() |
40.57 ![]() |
2021-07-09 09:00 DST ![]() |
LG3 ![]() |
63.433 ![]() |
49.9326 ![]() |
2021-07-09 10:00 DST ![]() |
LG1 ![]() |
53.6577 ![]() |
86.6658 ![]() |
2021-07-09 10:00 DST ![]() |
LG2 ![]() |
36.384 ![]() |
41.7439 ![]() |
2021-07-09 10:00 DST ![]() |
LG3 ![]() |
54.5699 ![]() |
54.0306 ![]() |
2021-07-10 09:00 DST ![]() |
LG1 ![]() |
35.2818 ![]() |
75.8487 ![]() |
2021-07-10 09:00 DST ![]() |
LG2 ![]() |
34.101 ![]() |
37.7934 ![]() |
2021-07-10 09:00 DST ![]() |
LG3 ![]() |
50.4009 ![]() |
46.8263 ![]() |
2021-07-10 10:00 DST ![]() |
LG1 ![]() |
39.3575 ![]() |
78.3179 ![]() |
2021-07-10 10:00 DST ![]() |
LG2 ![]() |
50.3955 ![]() |
43.3913 ![]() |
2021-07-10 10:00 DST ![]() |
LG3 ![]() |
52.2898 ![]() |
51.8793 ![]() |
2021-07-11 09:00 DST ![]() |
LG1 ![]() |
36.8559 ![]() |
71.9565 ![]() |
2021-07-11 09:00 DST ![]() |
LG2 ![]() |
31.1939 ![]() |
35.8108 ![]() |
2021-07-11 09:00 DST ![]() |
LG3 ![]() |
44.6744 ![]() |
49.5196 ![]() |
2021-07-11 10:00 DST ![]() |
LG1 ![]() |
43.9611 ![]() |
74.5974 ![]() |
2021-07-11 10:00 DST ![]() |
LG2 ![]() |
39.075 ![]() |
36.9884 ![]() |
2021-07-11 10:00 DST ![]() |
LG3 ![]() |
41.0939 ![]() |
45.0962 ![]() |
I want the x-axis to be Time, and then plot a line in the graph for Usage1 and Usage2 for each Type.我希望 x 轴是时间,然后在图中为每个类型的 Usage1 和 Usage2 绘制一条线。 So in total, since there are 3 different Types, there should be a total of 6 lines.
所以总的来说,因为有3种不同的类型,所以总共应该有6行。 So far I've tried the following code but it plots a single line for each Usage:
到目前为止,我已经尝试了以下代码,但它为每个用法绘制了一行:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_excel (r'plot.xlsx')
plt.plot( 'Time', 'Usage1 [%]', data=df, marker='o', linewidth=2, label='Type')
plt.plot( 'Time', 'Usage2 [%]', data=df, marker='o', linewidth=2, label='Type')
plt.legend(loc='best')
You will need to reshape your data to look like this using pandas.melt :您需要使用pandas.melt将数据重塑为如下所示:
Time Type variable value
0 2021-07-09 09:00 DST LG1 Usage1 [%] 60.0581
1 2021-07-09 09:00 DST LG2 Usage1 [%] 42.1409
2 2021-07-09 09:00 DST LG3 Usage1 [%] 63.4330
3 2021-07-09 10:00 DST LG1 Usage1 [%] 53.6577
4 2021-07-09 10:00 DST LG2 Usage1 [%] 36.3840
Then you can use seaborn.lineplot :然后你可以使用seaborn.lineplot :
import seaborn as sns
df['Time'] = pd.to_datetime(df['Time'])
sns.lineplot(data=df.melt(id_vars=['Time', 'Type']), x='Time', hue='Type', style='variable', y='value')
output:输出:
NB.注意。 to ensure consistent time handling, it is better to use the datetime format for your time column.
为确保一致的时间处理,最好为您的时间列使用日期时间格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.