배열을 사용하여 그래프 그리기
그래프에 그리려는 데이터 세트가 있습니다. 시간당 그룹화하려는 타임 스탬프 목록이 있고 선 그래프로 시간당 포인트의 양을보고 싶습니다 (하루에 여러 날의 데이터가 있고 하루에 그래프로 원하는 데이터가 있음) ).
나는 시간당 포인트의 가치를 가지고 있으며 포인트가 발생하는 시간을 가지고 있습니다. 내 그래프에 선을 표시하는 것이 작동하지 않고 간단한 해결책이 없다고 생각합니다. 사진도 올렸으니 출력을 볼 수 있습니다. 라인을 표시하려면 다음 단계는 무엇입니까?
다음 코드가 있습니다.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import csv
from datetime import timedelta
import datetime as dt
data= pd.read_csv('test2.csv', header=0, index_col=None, parse_dates=True, sep=';', usecols=[0,1])
df=pd.DataFrame(data, columns=['Date', 'Time'])
df['DateTime'] = df['Date'] + df['Time']
#for date in df['DateTime']:
def RemoveMilliSeconds(x):
return x[:-5]
df['Time'] = df['Time'].apply(RemoveMilliSeconds)
df['DateTime'] = df['Date'] + df['Time']
df['DateTime'] = pd.to_datetime(df['DateTime'], format="%Y:%m:%d %H:%M:%S")
df['TimeDelta'] = df.groupby('Date')['DateTime'].apply(lambda x: x.diff())
#print(df['TimeDelta'] / np.timedelta64(1, 'h'))
df['HourOfDay'] = df['DateTime'].dt.hour
df['Day'] = df['DateTime'].dt.day
grouped_df = df.groupby('Day')
for key, item in grouped_df:
print(grouped_df.get_group(key)['HourOfDay'].value_counts(), "\n\n")
res=[]
for i in df['DateTime'].dt.hour:
if i not in res:
res.append(i)
print("enkele lijst:" + str(res))
#range = (0,24)
#bins = 2
#plt.hist(df['DateTime'].dt.hour, bins, range)
x=np.array([res])
y=np.array([df['HourOfDay'].value_counts()])
plt.plot(x,y)
plt.show()
#times = pd.DatetimeIndex(df.Time)
#grouped = df.groupby([times.hour])
출력을 보여주는 그림

내 샘플 데이터 :
Date;Time
2020:02:13 ;12:39:02:913
2020:02:13 ;12:39:42:915
2020:02:13 ;13:06:20:718
2020:02:13 ;13:18:25:988
2020:02:13 ;13:34:02:835
2020:02:13 ;13:46:35:793
2020:02:13 ;13:59:10:659
2020:02:13 ;14:14:33:571
2020:02:13 ;14:25:36:381
2020:02:13 ;14:35:38:342
2020:02:13 ;14:46:04:006
2020:02:13 ;14:56:57:346
2020:02:13 ;15:07:39:752
2020:02:13 ;15:19:44:868
2020:02:13 ;15:32:31:438
2020:02:13 ;15:44:44:928
2020:02:13 ;15:56:54:453
2020:02:13 ;16:08:21:023
2020:02:13 ;16:19:17:620
2020:02:13 ;16:29:56:944
2020:02:13 ;16:40:11:132
2020:02:13 ;16:49:12:113
2020:02:13 ;16:57:26:652
2020:02:13 ;16:57:26:652
2020:02:13 ;17:04:22:092
2020:02:17 ;08:58:08:562
2020:02:17 ;08:58:42:545
답변
matplotlib
그들의 관계를 이해할 수 있는 방식으로 xy 데이터를 준비하지 않았습니다 .
쉬운 "답변"은 플롯 res
하고 df['HourOfDay'].value_counts()
서로에 대해 직접적으로 반대하는 것입니다.
#.....
#range = (0,24)
#bins = 2
#plt.hist(df['DateTime'].dt.hour, bins, range)
plt.plot(res, df['HourOfDay'].value_counts())
plt.show()
그러나 샘플 출력은 문제를 보여줍니다.

matplotlib
-값을 주문하지 않습니다 x
(다른 컨텍스트에서 데이터를 잘못 표시 할 수 있음). 따라서 플로팅하기 전에이 작업을 수행해야합니다.
#.....
#range = (0,24)
#bins = 2
#plt.hist(df['DateTime'].dt.hour, bins, range)
xy=np.stack((res, df['HourOfDay'].value_counts()))
xy = xy[:, np.argsort(xy[0,:])]
plt.plot(*xy)
plt.show()
이제 x
-values는 올바른 순서이며 y
-value는 xy
이 목적을 위해 만든 결합 된 배열 에서 정렬되었습니다 .

물론, 준비하는 것이 좋습니다 것 res
그리고 df['HourOfDay'].value_counts()
우리가 함께 정렬 결합 된 배열을 만들 필요가 없습니다, 직접. 코드가 수행해야하는 작업에 대한 설명을 제공하지 않았으므로 코드가 생성 한 문제를 사후 수정 만 할 수 있습니다. 처음부터이 문제가 발생하지 않도록 코드를 다르게 구성해야합니다. 그러나 당신 만이 이것을 할 수 있습니다 (또는 당신의 코드의 의도를 이해하는 사람들-저는 아닙니다).
나는 또한 유익한 matplotlib 튜토리얼 과 함께 시간을 보내는 것이 좋습니다 .이 시간은 낭비되지 않습니다.
업데이트
매일 서브 플롯을 만들고 시간당 항목 수를 계산하려고하는 것 같습니다. 나는 다음과 같이 접근 할 것입니다 (하지만 일부 팬더 전문가가 이에 대한 더 나은 방법을 가지고 있다고 확신합니다) :
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#read your data and create datetime index
df= pd.read_csv('test1.txt', sep=";")
df.index = pd.to_datetime(df["Date"]+df["Time"].str[:-5], format="%Y:%m:%d %H:%M:%S")
#group by date and hour, count entries
dfcounts = df.groupby([df.index.date, df.index.hour]).size().reset_index()
dfcounts.columns = ["Date", "Hour", "Count"]
maxcount = dfcounts.Count.max()
#group by date for plotting
dfplot = dfcounts.groupby(dfcounts.Date)
#plot each day into its own subplot
fig, axs = plt.subplots(dfplot.ngroups, figsize=(6,8))
for i, groupdate in enumerate(dfplot.groups):
ax=axs[i]
#the marker is not really necessary but has been added in case there is just one entry per day
ax.plot(dfplot.get_group(groupdate).Hour, dfplot.get_group(groupdate).Count, color="blue", marker="o")
ax.set_title(str(groupdate))
ax.set_xlim(0, 24)
ax.set_ylim(0, maxcount * 1.1)
ax.xaxis.set_ticks(np.arange(0, 25, 2))
plt.tight_layout()
plt.show()
샘플 출력 :

업데이트 2
개별 그림으로 플롯하려면 루프를 수정할 수 있습니다.
#...
dfplot = dfcounts.groupby(dfcounts.Date)
for groupdate in dfplot.groups:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
fig.suptitle("Date:"+str(groupdate), fontsize=16)
#scaled for comparability among graphs
ax1.plot(dfplot.get_group(groupdate).Hour, dfplot.get_group(groupdate).Count, color="blue", marker="o")
ax1.set_xlim(0, 24)
ax1.xaxis.set_ticks(np.arange(0, 25, 2))
ax1.set_ylim(0, maxcount * 1.1)
ax1.set_title("comparable version")
#scaled to maximize visibility per day
ax2.plot(dfplot.get_group(groupdate).Hour, dfplot.get_group(groupdate).Count, color="red", marker="x")
ax2.set_xlim(0, 24)
ax2.xaxis.set_ticks(np.arange(0, 25, 2))
ax2.set_title("expanded version")
plt.tight_layout()
#save optionally
#plt.savefig("MyDataForDay"+str(groupdate)+".eps")
print("All figures generated")
plt.show()
하루 중 하나에 대한 샘플 출력 :

다음 테스트 데이터로 생성되었습니다.
Date;Time
2020:02:13 ;12:39:02:913
2020:02:13 ;12:39:42:915
2020:02:13 ;13:06:20:718
2020:02:13 ;13:18:25:988
2020:02:13 ;13:34:02:835
2020:02:13 ;13:46:35:793
2020:02:13 ;13:59:10:659
2020:02:13 ;14:14:33:571
2020:02:13 ;14:25:36:381
2020:02:13 ;14:35:38:342
2020:02:13 ;14:46:04:006
2020:02:13 ;14:56:57:346
2020:02:13 ;15:07:39:752
2020:02:13 ;15:19:44:868
2020:02:13 ;15:32:31:438
2020:02:13 ;15:44:44:928
2020:02:13 ;15:56:54:453
2020:02:13 ;16:08:21:023
2020:02:13 ;16:19:17:620
2020:02:13 ;16:29:56:944
2020:02:13 ;16:40:11:132
2020:02:13 ;16:49:12:113
2020:02:13 ;16:57:26:652
2020:02:13 ;16:57:26:652
2020:02:13 ;17:04:22:092
2020:02:17 ;08:58:08:562
2020:02:17 ;08:58:42:545
2020:02:17 ;15:19:44:868
2020:02:17 ;17:32:31:438
2020:02:17 ;17:44:44:928
2020:02:17 ;17:56:54:453
2020:02:17 ;18:08:21:023
2020:03:19 ;06:19:17:620
2020:03:19 ;06:29:56:944
2020:03:19 ;06:40:11:132
2020:03:19 ;14:49:12:113
2020:03:19 ;16:57:26:652
2020:03:19 ;16:57:26:652
2020:03:19 ;17:04:22:092
2020:03:19 ;18:58:08:562
2020:03:19 ;18:58:42:545