Hello! Basically my thing is that when generating a graph with the code below the graphs look different when uploading an excel file vs a txt file even though they both have the same data. The excel file generates the graph perfectly and the txt file has some issues on the axis. However when they are both uploaded at the same time it generates the desired graph. I was wondering if anyone would be able to help me understand why this is happening.
I have attached images of the different data sets, and images of the graph behvior.
TXT File Example Graph
EXCEL File Example Graph
Both Files Example Graph
Example Excel Data
Example TXT File Data
Thank You, please let me know if you have any questions.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objects as go
import io
import base64
# Initialize the Dash app
app = dash.Dash(__name__)
# Layout of the Dash app
app.layout = html.Div([
html.H1("Graph acting different"),
# Drag and Drop area for file upload (multiple files allowed)
dcc.Upload(
id='upload-data',
children=html.Button("Drag and Drop or Select Excel/CSV Files"),
multiple=True, # Allow multiple files
accept='.xlsx, .txt' # Accept both .xlsx and .csv files
),
# Graphs to plot the data
dcc.Graph(id='graph-output'),
dcc.Graph(id='graph-output-2'),
dcc.Graph(id='graph-output-3'),
html.Div(id='data-preview')
])
# Callback to handle file upload and graph plotting
@app.callback(
[Output('graph-output', 'figure'),
Output('graph-output-2', 'figure'),
Output('graph-output-3', 'figure'),
Output('data-preview', 'children')],
[Input('upload-data', 'contents'),
Input('upload-data', 'filename')]
)
def update_graph(uploaded_files, filenames):
if uploaded_files is None:
return {}, {}, {}, "No files uploaded"
preview_data = [] # To store the preview for display
# Initialize the plots
fig1 = go.Figure()
fig2 = go.Figure()
fig3 = go.Figure()
# Loop through each uploaded file
for idx, uploaded_file in enumerate(uploaded_files):
content_type, content_string = uploaded_file.split(',')
decoded = base64.b64decode(content_string)
try:
# Check file type by file extension
if filenames[idx].endswith('.xlsx'):
# Read the Excel file into a DataFrame
df = pd.read_excel(io.BytesIO(decoded), skiprows=[0])
df = df.loc[(df != 0).any(axis=1)]
df[(df != 0).all(1)]
df = df[df['a'] != 0]
df = df[df['b'] != 0]
TXT = 0
print(TXT)
print("EXCEL TEXT")
file_name = filenames[idx]
fig1.add_trace(
go.Scatter(
x=df.iloc[:, 2],
y=df.iloc[:, 1],
mode='lines', # Use lines to connect data points
name=file_name
)
)
# Plot for second graph (x: column 10, y: column 4)
fig2.add_trace(
go.Scatter(
x=df.iloc[:, 9],
y=df.iloc[:, 3],
mode='lines', # Use lines to connect data points
name=file_name
)
)
# Plot for third graph (x: column 10, y: column 2)
fig3.add_trace(
go.Scatter(
x=df.iloc[:, 9],
y=df.iloc[:, 1],
mode='lines', # Use lines to connect data points
name=file_name
)
)
print("second o")
print(TXT)
if 'a' in df:
df = df.rename(
{'b': 'bb'}, axis=1)
# df['Scratch Depth (Β΅m)'] *= -1
print(df)
else:
return html.Div([
'Not Acceptable File'
])
elif filenames[idx].endswith('.TXT'):
# Read the CSV file into a DataFrame
df = pd.read_csv(io.BytesIO(decoded), encoding='unicode_escape', names=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
sep='\t ', engine='python')
df = df.loc[(df != 0).any(axis=1)]
df[(df != 0).all(1)]
df = df[df['a'] != 0]
df = df[df['b'] != 0]
df = df.dropna(thresh=3)
print(df)
TXT = 1
print(TXT)
print("CSV TEXT")
file_name = filenames[idx]
fig1.add_trace(
go.Scatter(
x=df.iloc[:, 2],
y=df.iloc[:, 1],
mode='lines', # Use lines to connect data points
name=file_name
)
)
# Plot for second graph (x: column 10, y: column 4)
fig2.add_trace(
go.Scatter(
x=df.iloc[:, 9],
y=df.iloc[:, 3],
mode='lines', # Use lines to connect data points
name=file_name
)
)
# Plot for third graph (x: column 10, y: column 2)
fig3.add_trace(
go.Scatter(
x=df.iloc[:, 9],
y=df.iloc[:, 1],
mode='lines', # Use lines to connect data points
name=file_name
)
)
print("second 1")
else:
return {}, {}, {}, "Unsupported file format"
except Exception as e:
return {}, {}, {}, f"Error processing file: {str(e)}"
# Plot for first graph (x: column 1, y: column 2)
# Flatten preview data to show all rows from all files
preview = [item for sublist in preview_data for item in sublist]
# Update the layout of the first figure (add titles and labels)
fig1.update_layout(
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
xaxis_title="a",
yaxis_title="b",
showlegend=True
)
fig1.update_layout(
title="b vs a",
height=800,
)
fig1.update_layout(
title={
'y': 0.925,
'x': 0.5,
'xanchor': 'center',
'yanchor': 'top'
}
)
fig1.update_yaxes(autorange="reversed")
# Update the layout of the second figure (add titles and labels)
fig2.update_layout(
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
xaxis_title="j",
yaxis_title="d",
showlegend=True
)
fig2.update_layout(
title="d vs j",
height=800,
)
fig2.update_layout(
title={
'y': 0.925,
'x': 0.5,
'xanchor': 'center',
'yanchor': 'top'
}
)
# Update the layout of the third figure (add titles and labels)
fig3.update_layout(
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
),
xaxis_title="j",
yaxis_title="b",
showlegend=True
)
fig3.update_layout(
title="b vs j",
height=800,
)
fig3.update_layout(
title={
'y': 0.925,
'x': 0.5,
'xanchor': 'center',
'yanchor': 'top'
}
)
fig3.update_yaxes(autorange="reversed")
return fig1, fig2, fig3, preview
if __name__ == '__main__':
app.run(debug=True)