I am trying to plot a number of bar charts with matplotlib having exactly 26 timestamps / slots at the x-axis and two integers for the y-axis. For most data sets this scales fine, but in some cases matplotlib lets the bars overlap:
Left overlapping and not aligned to xticks, right one OK
Overlapping
So instead of giving enough space for the bars they are overlapping although my width is set to 0.1 and my datasets have 26 values, which I checked.
My code to plot these charts is as follows:
# Plot something
rows = len(data_dict) // 2 + 1
fig = plt.figure(figsize=(15, 5*rows))
gs1 = gridspec.GridSpec(rows, 2)
grid_x = 0
grid_y = 0
for dataset_name in data_dict:
message1_list = []
message2_list = []
ts_list = []
slot_list = []
for slot, counts in data_dict[dataset_name].items():
slot_list.append(slot)
message1_list.append(counts["Message1"])
message2_list.append(counts["Message2"])
ts_list.append(counts["TS"])
ax = fig.add_subplot(gs1[grid_y, grid_x])
ax.set_title("Activity: " + dataset_name, fontsize=24)
ax.set_xlabel("Timestamps", fontsize=14)
ax.set_ylabel("Number of messages", fontsize=14)
ax.xaxis_date()
hfmt = matplotdates.DateFormatter('%d.%m,%H:%M')
ax.xaxis.set_major_formatter(hfmt)
ax.set_xticks(ts_list)
plt.setp(ax.get_xticklabels(), rotation=60, ha='right')
ax.tick_params(axis='x', pad=0.75, length=5.0)
rects = ax.bar(ts_list, message2_list, align='center', width=0.1)
rects2 = ax.bar(ts_list, message1_list, align='center', width=0.1, bottom=message2_list)
# update grid position
if (grid_x == 1):
grid_x = 0
grid_y += 1
else:
grid_x = 1
plt.tight_layout(0.01)
plt.savefig(r"output_files\activity_barcharts.svg",bbox_inches='tight')
plt.gcf().clear()
The input data looks as follows (example of a plot with overlapping bars, second picture)
slot - message1 - message2 - timestamp
0 - 0 - 42 - 2017-09-11 07:59:53.517000+00:00
1 - 0 - 4 - 2017-09-11 09:02:28.827875+00:00
2 - 0 - 0 - 2017-09-11 10:05:04.138750+00:00
3 - 0 - 0 - 2017-09-11 11:07:39.449625+00:00
4 - 0 - 0 - 2017-09-11 12:10:14.760500+00:00
5 - 0 - 0 - 2017-09-11 13:12:50.071375+00:00
6 - 0 - 13 - 2017-09-11 14:15:25.382250+00:00
7 - 0 - 0 - 2017-09-11 15:18:00.693125+00:00
8 - 0 - 0 - 2017-09-11 16:20:36.004000+00:00
9 - 0 - 0 - 2017-09-11 17:23:11.314875+00:00
10 - 0 - 0 - 2017-09-11 18:25:46.625750+00:00
11 - 0 - 0 - 2017-09-11 19:28:21.936625+00:00
12 - 0 - 0 - 2017-09-11 20:30:57.247500+00:00
13 - 0 - 0 - 2017-09-11 21:33:32.558375+00:00
14 - 0 - 0 - 2017-09-11 22:36:07.869250+00:00
15 - 0 - 0 - 2017-09-11 23:38:43.180125+00:00
16 - 0 - 0 - 2017-09-12 00:41:18.491000+00:00
17 - 0 - 0 - 2017-09-12 01:43:53.801875+00:00
18 - 0 - 0 - 2017-09-12 02:46:29.112750+00:00
19 - 0 - 0 - 2017-09-12 03:49:04.423625+00:00
20 - 0 - 0 - 2017-09-12 04:51:39.734500+00:00
21 - 0 - 0 - 2017-09-12 05:54:15.045375+00:00
22 - 0 - 0 - 2017-09-12 06:56:50.356250+00:00
23 - 0 - 0 - 2017-09-12 07:59:25.667125+00:00
24 - 0 - 20 - 2017-09-12 09:02:00.978000+00:00
25 - 0 - 0 - 2017-09-12 10:04:36.288875+00:00
Does anyone know how to prevent this from happening?
I calculated exactly 26 bars for every chart and actually expected them to have equally width. I also tried to replace the 0 with 1e-5, but that did not prevent any overlapping (which another post proposed).
The width of the bar is the width in data units. I.e. if you want to have a bar of width 1 minute, you would set the width to
plt.bar(..., width=1./(24*60.))
because the numeric axis unit for datetime axes in matplotlib is days and there are 24*60 minutes in a day.
For an automatic determination of the bar width, you may say that you want to have the bar width the smallest difference between any two successive values from the input time list. In that case, something like the following will do the trick
import numpy as np
import matplotlib.pyplot as plt
import datetime
import matplotlib.dates
t = [datetime.datetime(2017,9,12,8,i) for i in range(60)]
x = np.random.rand(60)
td = np.diff(t).min()
s1 = matplotlib.dates.date2num(datetime.datetime.now())
s2 = matplotlib.dates.date2num(datetime.datetime.now()+td)
plt.bar(t, x, width=s2-s1, ec="k")
plt.show()
Related
I have a code which will plot multiple plots using matplotlib.My code is give below.
index = LFRO_tdms["Measurement Config"].as_dataframe()["Frequencies"]
for vdd in set_vdds:
for DUT in unique_DUTs:
temp_df = df[ (df["Serial"] == str(DUT)) & (df["VDD (V)"]==vdd) ]
temp_df["Serial ID - Temp(C)"] = temp_df["Serial"] + " - " + temp_df["Target Temp (°C)"].astype(dtype=str)
df_LFRO_data_to_plot = df_LFRO[temp_df["#Magnitude"].to_numpy(dtype=str)]
df_LFRO_data_to_plot.index = index
df_LFRO_data_to_plot.columns = temp_df["Serial ID - Temp(C)"]
df_LFRO_data_to_plot.plot(logx=True, colormap="jet")
plt.title("Unit: "+ DUT + " Vdd: " + str(vdd))
afetr running this code it will output multiple plots 12 0r 13 nos as shown below.
I need to implement the same using plotly.below is my code,but it is outputting plots in a different way.
fig = go.Figure()
index = LFRO_tdms["Measurement Config"].as_dataframe()["Frequencies"]
for vdd in set_vdds:
for DUT in unique_DUTs:
temp_df = df[ (df["Serial"] == str(DUT)) & (df["VDD (V)"]==vdd) ]
temp_df["Serial ID - Temp(C)"] = temp_df["Serial"] + " - " + temp_df["Target Temp (°C)"].astype(dtype=str)
df_LFRO_data_to_plot = df_LFRO[temp_df["#Magnitude"].to_numpy(dtype=str)]
df_LFRO_data_to_plot.index = index
df_LFRO_data_to_plot.columns = temp_df["Serial ID - Temp(C)"]
# df_LFRO_data_to_plot.plot(logx=True, colormap="jet")
# plt.title("Unit: "+ DUT + " Vdd: " + str(vdd))
fig.add_traces(go.Scatter(x=df_LFRO_data_to_plot.index, y=df_LFRO_data_to_plot.columns, mode='lines', name = ("Unit: "+ DUT + " Vdd: " + str(vdd))))
fig.show()
I need the plots to come as shown in the 1st image. May I know what mistake I am making.
Test Station Position Serial Timestamp ETC Temp (°C) ETC Pressure (kPa) ETC Humidity (%RH) Ref Mic Temp (°C) Site Temp (°C) Target Temp (°C) VDD (V) LFRO (Hz) #Magnitude
0 1 1 1 07LX-1 2022-11-17 23:05:51.591926 23.151848 99.334515 3.564379 14.349645 -30.041135 -35.0 1.60 9.221194 0
1 1 1 2 07LX-2 2022-11-17 23:05:51.591926 23.151848 99.334515 3.564379 14.349645 -30.257592 -35.0 1.60 8.995556 1
2 1 1 3 07LX-3 2022-11-17 23:05:51.591926 23.151848 99.334515 3.564379 14.349645 -30.511629 -35.0 1.60 9.452866 2
3 1 1 4 07LX-4 2022-11-17 23:05:51.591926 23.151848 99.334515 3.564379 14.349645 -29.863173 -35.0 1.60 9.299079 3
4 1 1 1 07LX-1 2022-11-17 23:09:41.373825 22.475499 99.338778 3.574306 12.311989 -28.114924 -35.0 1.66 7.390171 4
I'm trying to scrape table data off of this website:
https://www.nfl.com/standings/league/2019/REG
I have working code (below), however, it seems like the table data is not in the order that I see on the website.
On the website I see (top-down):
Baltimore Ravens, Green Bay Packers, ..., Cincinatti Bengals
But in my code results, I see (top-down): Bengals, Lions, ..., Ravens
Why is soup returning the tags out of order? Does anyone know why this is happening? Thanks!
import requests
import urllib.request
from bs4 import BeautifulSoup
import pandas as pd
import lxml
url = 'https://www.nfl.com/standings/league/2019/REG'
soup = BeautifulSoup(requests.get(url).text, 'lxml')
print(soup) #not sure why soup isn't returning tags in the order I see on website
table = soup.table
headers = []
for th in table.select('th'):
headers.append(th.text)
print(headers)
df = pd.DataFrame(columns=headers)
for sup in table.select('sup'):
sup.decompose() #Removes sup tag from the table tree so x, xz* in nfl_team_name will not show up
for tr in table.select('tr')[1:]:
td_list = tr.select('td')
td_str_list = [td_list[0].select('.d3-o-club-shortname')[0].text]
td_str_list = td_str_list + [td.text for td in td_list[1:]]
df.loc[len(df)] = td_str_list
print(df.to_string())
After initial load the table is dynamically sorted by column PCT - To get your goal do the same with your DataFrame using sort_values():
pd.read_html('https://www.nfl.com/standings/league/2019/REG')[0].sort_values(by='PCT',ascending=False)
Or based on your example:
df.sort_values(by='PCT',ascending=False)
Output:
NFL Team
W
L
T
PCT
PF
PA
Net Pts
Home
Road
Div
Pct
Conf
Pct
Non-Conf
Strk
Last 5
Ravens
14
2
0
0.875
531
282
249
7 - 1 - 0
7 - 1 - 0
5 - 1 - 0
0.833
10 - 2 - 0
0.833
4 - 0 - 0
12W
5 - 0 - 0
49ers
13
3
0
0.813
479
310
169
6 - 2 - 0
7 - 1 - 0
5 - 1 - 0
0.833
10 - 2 - 0
0.833
3 - 1 - 0
2W
3 - 2 - 0
Saints
13
3
0
0.813
458
341
117
6 - 2 - 0
7 - 1 - 0
5 - 1 - 0
0.833
9 - 3 - 0
0.75
4 - 0 - 0
3W
4 - 1 - 0
Packers
13
3
0
0.813
376
313
63
7 - 1 - 0
6 - 2 - 0
6 - 0 - 0
1
10 - 2 - 0
0.833
3 - 1 - 0
5W
5 - 0 - 0
...
med_spotify = spotify_data.drop(columns=['name', 'explicit', 'artists', 'key', 'mode', 'time_signature', 'tempo', 'duration_ms', 'loudness'])
med_spotify = med_spotify.groupby('release_date').median()
med_spotify = med_spotify.reset_index()
merged = med_spotify['release_date'].to_frame()
merged['theta'] = [med_spotify.columns] * len(merged)
merged['r'] = np.nan
merged['r'] = merged['r'].astype('object')
for k in range(len(merged)):
merged.at[k, 'r'] = med_spotify.iloc[k].to_list()
fig4 = px.line_polar(merged, r='r', theta='theta', animation_frame='release_date', line_close=True)
fig4.show()
how the plot looks in the browser
I have a dataframe with songs from spotify, then I've made a dataframe with the median of the columns for every year. Now I want to represent that information in a line polar chart animation.
https://medium.com/#marcosanchezayala/plotting-pokemon-attributes-plotly-polar-plots-and-animations-319934b60f0e
This article shows something similar but omits the code that explains how it was done.
Changing the theta parameter to a list of column names to use as radii gives an error saying that the length has to be the same as the r parameter.
This code shows a empty plot but no errors.
I've tried every way I know to make this work the last two days and searched everywhere in the internet and there's no code examples of px.line_polar charts animated.
Thank you
spotify_data example:
name duration_ms explicit \
0 Carve 126903 0
1 Capítulo 2.16 - Banquero Anarquista 98200 0
2 Vivo para Quererte - Remasterizado 181640 0
3 El Prisionero - Remasterizado 176907 0
4 Lady of the Evening 163080 0
artists release_date danceability energy key loudness \
0 ['Uli'] 1922 0.645 0.4450 0 -13.338
1 ['Fernando Pessoa'] 1922 0.695 0.2630 0 -22.136
2 ['Ignacio Corsini'] 1922 0.434 0.1770 1 -21.180
3 ['Ignacio Corsini'] 1922 0.321 0.0946 7 -27.961
4 ['Dick Haymes'] 1922 0.402 0.1580 3 -16.900
mode speechiness acousticness instrumentalness liveness valence \
0 1 0.4510 0.674 0.7440 0.151 0.127
1 1 0.9570 0.797 0.0000 0.148 0.655
2 1 0.0512 0.994 0.0218 0.212 0.457
3 1 0.0504 0.995 0.9180 0.104 0.397
4 0 0.0390 0.989 0.1300 0.311 0.196
tempo time_signature
0 104.851 3
1 102.009 1
2 130.418 5
3 169.980 3
4 103.220 4
Since the given data is in wide format, it can be converted to long format to make the data usable for graphing. The data provided was partial data, so I copied the same data and added the year. pd.melt() should refer to this.
med_spotify = spotify_data.drop(columns=['name', 'explicit', 'artists', 'key', 'mode', 'time_signature', 'tempo', 'duration_ms', 'loudness'])
med_spotify = med_spotify.groupby('release_date').median()
med_spotify.reset_index(inplace=True)
plot_data = pd.melt(med_spotify, id_vars='release_date', var_name='attribute', value_name='attribute_value')
import plotly.express as px
fig = px.line_polar(plot_data,
r='attribute_value',
theta='attribute',
line_close=True,
animation_frame = 'release_date',
title='Spotify',
template = 'ggplot2'
)
fig.update_layout(
autosize=False,
height=600,
width=800,
)
fig.show()
I would like to calculate the average slope of multiple numbers. For example:
I've been given 5 numbers (eg. 1.1523, 1.4626, 1.5734, 1.8583, 1.6899). I get a new number every 15 minutes and delete the oldest and want to calculate again the average slope.
I've already seen formulas but I don't really get how to calculate it when like the imaginary x-axis is the time. Like I have:
X: 14:00, 14:15, 14:30, 14:45, 15:00
Y: 1.1523, 1.4626, 1.5734, 1.8583, 1.6899
Assuming all times are in HH:MM format and we don't need to worry about passing midnight, this should work:
X = ['14:00', '14:15', '14:30', '14:45', '15:00']
Y = [1.1523, 1.4626, 1.5734, 1.8583, 1.6899]
minutes = [int(s[:2]) * 60 + int(s[3:]) for s in X]
slope = (Y[-1] - Y[0]) / ((minutes[-1] - minutes[0]) / 60)
print(slope)
slopes = [(Y[i] - Y[i - 1]) / ((minutes[i] - minutes[i - 1]) / 60) for i in range(1, len(X))]
print(slopes)
averageSlope = sum(slopes) / (len(X) - 1)
print(averageSlope)
Results:
0.5375999999999999
[1.2411999999999992, 0.44320000000000004, 1.1396000000000006, -0.6736000000000004]
0.5375999999999999
I could be wrong, but isn't average slope determined the same way as average velocity - which is Delta d / Delta t? If that is the case, shouldn't it be Delta Y / Delta X?
from datetime import datetime
X = ['14:00', '14:15', '14:30', '14:45', '15:00']
Y = [1.1523, 1.4626, 1.5734, 1.8583, 1.6899]
today = datetime.now()
avg = []
for i in range(len(X) - 1):
e = X[i + 1].split(":")
e = datetime(today.year, today.month, today.day, int(e[0]), int(e[1]))
s = X[i].split(":")
s = datetime(today.year, today.month, today.day, int(s[0]), int(s[1]))
deltaX = e - s
deltaY = Y[i + 1] - Y[i]
ans = (deltaY / deltaX.seconds) / 60
avg.append(f'{ans:.9f}')
print(avg)
['0.000005746', '0.000002052', '0.000005276', '-0.000003119']
Consider this data:
1 minute(s) 1 meter(s)
2 minute(s) 2 meter(s)
3 minute(s) 3 meter(s)
You should have a slope of 1 meter/minute, no matter how you cut the cake.
Likewise for this:
1 minute(s) 2 meter(s)
2 minute(s) 3 meter(s)
3 minute(s) 5 meter(s)
From 2 to 1 minutes, the average is 1 meters/minute, from 3 to 2 minutes its 2 meters/minute, and from 3 to 1 minutes its 1.5 meters/minute.
I have written a code to perform some data cleaning to get the final columns and values from a tab spaced file.
import matplotlib.image as image
import numpy as np
import tkinter as tk
import matplotlib.ticker as ticker
from tkinter import filedialog
import matplotlib.pyplot as plt
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
files1 = filedialog.askopenfilename(multiple=True)
files = root.tk.splitlist(files1)
List = list(files)
%gui tk
for i,file in enumerate(List,1):
d = pd.read_csv(file,sep=None,engine='python')
h = d.drop(d.index[19:])
transpose = h.T
header =transpose.iloc[0]
df = transpose[1:]
df.columns =header
df.columns = df.columns.str.strip()
all_columns = list(df)
df[all_columns] = df[all_columns].astype(str)
k =df.drop(columns =['Op:','Comment:','Mod Type:', 'PN', 'Irradiance:','Irr Correct:', 'Lamp Voltage:','Corrected To:', 'MCCC:', 'Rseries:', 'Rshunt:'], axis=1)
k.head()
I want to run this code to multiple files and do the same and concatenate all the results to one data frame.
for eg, If I select 20 files, then new data frame with one line of header and all the 20 results below with increasing order of the value from the column['Module Temp:'].
It would be great if someone could provide a solution to this problem
Please find the link to sample data:https://drive.google.com/drive/folders/1sL2-CwCGeGm0-fvcpzMVzgFnYzN3wzVb?usp=sharing
The following code shows how to parse the files and extract the data. It doesn't show the tkinter GUI component. files will represent your selected files.
Assumptions:
The first 92 rows of the files are always the measurement parameters
Rows from 93 are the measurements.
The 'Module Temp' for each file is different
The lists will be sorted based on the sort order of mod_temp, so the data will be in order in the DataFrame.
The list sorting uses the accepted answer to Sorting list based on values from another list?
import pandas as p
from patlib import Path
# set path to files
path_ = Path('e:/PythonProjects/stack_overflow/data/so_data/2020-11-16')
# select the correct files
files = path_.glob('*.ivc')
# create lists for metrics
measurement_params = list()
mod_temp = list()
measurements = list()
# iterate through the files
for f in files:
# get the first 92 rows with the measurement parameters
mp = pd.read_csv(f, sep='\t', nrows=91, index_col=0)
# remove the whitespace and : from the end of the index names
mp.index = mp.index.str.replace(':', '').str.strip().str.replace('\\s+', '_')
# get the column header
col = mp.columns[0]
# get the module temp
mt = mp.loc['Module_Temp', col]
# add Modult_Temp to mod_temp
mod_temp.append(float(mt))
# get the measurements
m = pd.read_csv(f, sep='\t', skiprows=92, nrows=3512)
# remove the whitespace and : from the end of the column names
m.columns = m.columns.str.replace(':', '').str.strip()
# add Module_Temp column
m['mod_temp'] = mt
# store the measure parameters
measurement_params.append(mp.T)
# store the measurements
measurements.append(m)
# sort lists based on mod_temp sort order
measurement_params = [x for _, x in sorted(zip(mod_temp, measurement_params))]
measurements = [x for _, x in sorted(zip(mod_temp, measurements))]
# create a dataframe for the measurement parameters
df_mp = pd.concat(measurement_params)
# create a dataframe for the measurements
df_m = pd.concat(measurements).reset_index(drop=True)
df_mp
Title: Comment Op ID Mod_Type PN Date Time Irradiance IrrCorr Irr_Correct Lamp_Voltage Module_Temp Corrected_To MCCC Voc Isc Rseries Rshunt Pmax Vpm Ipm Fill_Factor Active_Eff Aperture_Eff Segment_Area Segs_in_Ser Segs_in_Par Panel_Area Vload Ivld Pvld Frequency SweepDelay SweepLength SweepSlope SweepDir MCCC2 MCCC3 MCCC4 LampI IntV IntV2 IntV3 IntV4 LoadV PulseWidth1 PulseWidth2 PulseWidth3 PulseWidth4 TRef1 TRef2 TRef3 TRef4 MCMode Irradiance2 IrrCorr2 Voc2 Isc2 Pmax2 Vpm2 Ipm2 Fill_Factor2 Active_Eff2 ApertureEff2 LoadV2 PulseWidth12 PulseWidth22 Irradiance3 IrrCorr3 Voc3 Isc3 Pmax3 Vpm3 Ipm3 Fill_Factor3 Active_Eff3 ApertureEff3 LoadV3 PulseWidth13 PulseWidth23 RefCellID RefCellTemp RefCellIrrMM RefCelIscRaw RefCellIsc VTempCoeff ITempCoeff PTempCoeff MismatchCorr Serial_No Soft_Ver
Nease 345W N345M72 STC Admin MCIND2021-058 ModuleType1 NaN 10-09-2020 19:12:52 100.007 100 Ref Cell 2400 25.2787 25 1.3669 46.4379 9.13215 0.43411 294.467 331.924 38.3403 8.65732 0.78269 1.89434 1.7106 243.36 72 1 19404 0 0 0 218000 10 100 0.025 0 1 1.155 1.155 20.4736 6.87023 6.8645 6 6 6.76 107.683 109.977 0 0 27.2224 0 0 0 False -1.#INF 70 0 0 0 0 0 0 0 0 5 107.683 109.977 -1.#INF 40 0 0 0 0 0 0 0 0 5 107.683 109.977 WPVS mono C-Si Ref Cell 25.9834 1001.86 0.15142 0.15135 -0.31 0.05 -0.4 0.9985 S91-00052 5.5.1
Solarium SGE24P330 STC Admin MCIND_2021_0074 ModuleType1 NaN 17-09-2020 15:06:12 99.3671 100 Ref Cell 2400 25.3380 25 1.3669 45.2903 8.87987 0.48667 216.763 311.031 36.9665 8.41388 0.77338 1.77510 1.60292 243.36 72 1 19404 0 0 0 218000 10 100 0.025 0 1 1.155 1.155 20.405 6.82362 6.8212 6 6 6.6 107.660 109.977 0 0 25.9418 0 0 0 False -1.#INF 70 0 0 0 0 0 0 0 0 4.943 107.660 109.977 -1.#INF 40 0 0 0 0 0 0 0 0 4.943 107.660 109.977 WPVS mono C-Si Ref Cell 25.3315 998.370 0.15085 0.15082 -0.31 0.05 -0.4 0.9985 S91-00052 5.5.1
Nease 345W N345M72 STC Admin MCIND2021-058 ModuleType1 NaN 10-09-2020 19:11:32 100.010 100 Ref Cell 2400 25.3557 25 1.3669 46.4381 9.11368 0.41608 299.758 331.418 38.3876 8.63345 0.78308 1.89144 1.70798 243.36 72 1 19404 0 0 0 218000 10 100 0.025 0 1 1.155 1.155 20.3820 6.87018 6.8645 6 6 6.76 107.683 109.977 0 0 27.2535 0 0 0 False -1.#INF 70 0 0 0 0 0 0 0 0 5 107.683 109.977 -1.#INF 40 0 0 0 0 0 0 0 0 5 107.683 109.977 WPVS mono C-Si Ref Cell 25.9614 1003.80 0.15171 0.15164 -0.31 0.05 -0.4 0.9985 S91-00052 5.5.1
Nease 345W N345M72 STC Admin MCIND2021-058 ModuleType1 NaN 10-09-2020 19:14:09 99.9925 100 Ref Cell 2400 25.4279 25 1.3669 46.4445 9.14115 0.43428 291.524 332.156 38.2767 8.67776 0.78236 1.89566 1.71179 243.36 72 1 19404 0 0 0 218000 10 100 0.025 0 1 1.155 1.155 20.5044 6.87042 6.8645 6 6 6.76 107.660 109.977 0 0 27.1989 0 0 0 False -1.#INF 70 0 0 0 0 0 0 0 0 5 107.660 109.977 -1.#INF 40 0 0 0 0 0 0 0 0 5 107.660 109.977 WPVS mono C-Si Ref Cell 26.0274 1000.93 0.15128 0.15121 -0.31 0.05 -0.4 0.9985 S91-00052 5.5.1
df_m.head()
Voltage Current mod_temp
0 -1.193405 9.202885 25.2787
1 -1.196560 9.202489 25.2787
2 -1.193403 9.201693 25.2787
3 -1.196558 9.201298 25.2787
4 -1.199711 9.200106 25.2787
df_m.tail()
Voltage Current mod_temp
14043 46.30869 0.315269 25.4279
14044 46.31411 0.302567 25.4279
14045 46.31949 0.289468 25.4279
14046 46.32181 0.277163 25.4279
14047 46.33039 0.265255 25.4279
Plot
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(20, 8))
sns.scatterplot(x='Current', y='Voltage', data=df_m, hue='mod_temp', s=10)
plt.show()
Note
After doing this, I was having trouble plotting the data because the columns were not float type. However, an error occurred when trying to set the type. Looking back at the data, after row 92, there are multiple headers throughout the two columns.
Row 93: Voltage: Current:
Row 3631: Ref Cell: Lamp I:
Row 7169: Voltage2: Current2:
Row 11971: Ref Cell2: Lamp I2:
Row 16773: Voltage3: Current3:
Row 21575: Ref Cell3: Lamp I3:
Row 26377: Raw Voltage: Raw Current :
Row 29915: WPVS Voltage: WPVS Current:
I went back and used the nrows parameter when creating m, so only the first set of headers and associated measurements are extracted from the file.
I recommend writing a script using the csv module to read each file, and create a new file beginning at each blank row, this will make the files have consistent types of measurements.
This should be a new question, if needed.
There are various ways to do it. You can append one dataframe to another (basically stack one on top of the other), and you can do it in the loop. Here is an example. I use fake dfs but you will use your own
import pandas as pd
import numpy as np
combined = None
for _ in range(5):
# stub df creation -- you will use your real code here
df = pd.DataFrame(columns = ['Module Temp','A', 'B'], data = np.random.random((5,3)))
if combined is None:
# initialize with the first one
combined = df.copy()
else:
# add the next one
combined = combined.append(df, sort = False, ignore_index = True)
combined.sort_values('Module Temp', inplace = True)
Here combined will have all the dfs, sorted by 'Module Temp'