-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotly_chart_maker.py
More file actions
299 lines (260 loc) · 12.7 KB
/
plotly_chart_maker.py
File metadata and controls
299 lines (260 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import os
from io import BytesIO
import time
st.title('CSV to Chart Converter with Plotly')
# Use the environment variable if set, otherwise use a default path
output_dir = os.getenv('OUTPUT_DIR', os.path.join(os.getcwd(), 'output_charts'))
os.makedirs(output_dir, exist_ok=True)
print(f"Output directory set to: {output_dir}")
print(f"Absolute path: {os.path.abspath(output_dir)}")
# File uploader
uploaded_files = st.file_uploader("Choose CSV files", type="csv", accept_multiple_files=True)
if uploaded_files:
# Chart type selection
chart_types = ['Bar', 'Line', 'Scatter', 'Pie', 'Area']
selected_chart_type = st.selectbox('Choose chart type', chart_types)
# Color palette options
color_palette_options = list(px.colors.qualitative.__dict__.keys())
color_palette_options = [name for name in color_palette_options if not name.startswith('_') and isinstance(px.colors.qualitative.__dict__[name], list)]
# Create a dictionary to map palette names to their colors
palette_colors = {name: px.colors.qualitative.__dict__[name] for name in color_palette_options}
# Display palette previews in a vertical list
st.write("### Color Palette Previews")
# Use a selectbox for palette selection
selected_palette_name = st.selectbox('Choose a color palette', options=color_palette_options)
# Display the selected palette preview
if selected_palette_name:
colors = palette_colors[selected_palette_name]
color_swatches = ''.join([f'<div style="display: inline-block; width: 12px; height: 12px; margin-right: 2px; background-color: {color}; border: 1px solid #ddd;"></div>' for color in colors])
st.markdown(f"""
<div style="display: flex; align-items: center; margin-bottom: 10px;">
<span style="margin-right: 10px;">{selected_palette_name}</span>
<div style="display: flex;">{color_swatches}</div>
</div>
""", unsafe_allow_html=True)
# Show all palettes in an expander
with st.expander("View All Palettes", expanded=False):
for name in color_palette_options:
colors = palette_colors[name]
color_swatches = ''.join([f'<div style="display: inline-block; width: 12px; height: 12px; margin-right: 2px; background-color: {color}; border: 1px solid #ddd;"></div>' for color in colors])
st.markdown(f"""
<div style="display: flex; align-items: center; margin-bottom: 5px;">
<span style="margin-right: 10px; width: 150px;">{name}</span>
<div style="display: flex;">{color_swatches}</div>
</div>
""", unsafe_allow_html=True)
# Legend positioning options
legend_positions = ['top right', 'top left', 'bottom left', 'bottom right']
selected_legend_position = st.selectbox('Choose legend position', options=legend_positions)
# Text visibility options
show_x_label = st.checkbox('Show X-axis label', value=True)
show_y_label = st.checkbox('Show Y-axis label', value=True)
show_title = st.checkbox('Show Title', value=True)
# New options for bar values and background
show_bar_values = st.checkbox('Show bar values', value=True)
text_color = st.radio('Text color', ['Black', 'White'])
bg_color = st.radio('Background color', ['White', 'Black', 'Transparent'])
# Export options
export_format = st.selectbox('Export format', ['PNG', 'JPEG', 'SVG', 'PDF'])
def get_fig(data, chart_type, palette_name, filename=None):
colors = px.colors.qualitative.__dict__[palette_name]
# Determine text color based on background
if bg_color == 'White':
effective_text_color = 'black'
elif bg_color == 'Black':
effective_text_color = 'white'
else: # Transparent
effective_text_color = text_color.lower()
# Create figure with explicit height
fig = go.Figure()
if chart_type == 'Bar':
for i, col in enumerate(['Sim', 'Não', 'Ns/Nr']):
fig.add_trace(go.Bar(
x=data['concelhos'],
y=data[col],
name=col,
marker_color=colors[i % len(colors)],
text=data[col] if show_bar_values else None,
textposition='outside' if show_bar_values else None,
textfont=dict(color=effective_text_color)
))
fig.update_layout(barmode='group')
elif chart_type == 'Line':
for i, col in enumerate(['Sim', 'Não', 'Ns/Nr']):
fig.add_trace(go.Scatter(
x=data['concelhos'],
y=data[col],
name=col,
mode='lines+markers',
line=dict(color=colors[i % len(colors)]),
text=data[col] if show_bar_values else None,
textposition='top center' if show_bar_values else None,
textfont=dict(color=effective_text_color)
))
elif chart_type == 'Scatter':
for i, col in enumerate(['Sim', 'Não', 'Ns/Nr']):
fig.add_trace(go.Scatter(
x=data['concelhos'],
y=data[col],
name=col,
mode='markers',
marker=dict(color=colors[i % len(colors)]),
text=data[col] if show_bar_values else None,
textposition='top center' if show_bar_values else None,
textfont=dict(color=effective_text_color)
))
elif chart_type == 'Pie':
fig.add_trace(go.Pie(
labels=data.columns[1:],
values=data.iloc[0, 1:],
marker=dict(colors=colors[:len(data.columns[1:])]),
textinfo='label+percent' if show_bar_values else 'label',
textfont=dict(color=effective_text_color)
))
elif chart_type == 'Area':
for i, col in enumerate(['Sim', 'Não', 'Ns/Nr']):
fig.add_trace(go.Scatter(
x=data['concelhos'],
y=data[col],
name=col,
stackgroup='one',
fillcolor=colors[i % len(colors)],
line=dict(color=colors[i % len(colors)])
))
# Set background color and text color with soft gray grid lines
if bg_color == 'White':
fig.update_layout(
paper_bgcolor='white',
plot_bgcolor='white',
font=dict(color='black'),
xaxis=dict(
title=dict(font=dict(color='black')),
tickfont=dict(color='black'),
gridcolor='rgba(200, 200, 200, 0.3)',
showgrid=True,
range=[-0.5, len(data['concelhos'])-0.5]
),
yaxis=dict(
title=dict(font=dict(color='black')),
tickfont=dict(color='black'),
gridcolor='rgba(200, 200, 200, 0.3)',
showgrid=True,
autorange=True
),
legend=dict(font=dict(color='black')),
margin=dict(l=60, r=60, b=80, t=100, pad=10),
height=600,
autosize=False
)
elif bg_color == 'Black':
fig.update_layout(
paper_bgcolor='black',
plot_bgcolor='black',
font=dict(color='white'),
xaxis=dict(
title=dict(font=dict(color='white')),
tickfont=dict(color='white'),
gridcolor='rgba(100, 100, 100, 0.5)',
showgrid=True,
range=[-0.5, len(data['concelhos'])-0.5]
),
yaxis=dict(
title=dict(font=dict(color='white')),
tickfont=dict(color='white'),
gridcolor='rgba(100, 100, 100, 0.5)',
showgrid=True,
autorange=True
),
legend=dict(font=dict(color='white')),
margin=dict(l=60, r=60, b=80, t=100, pad=10),
height=600,
autosize=False
)
else: # Transparent
fig.update_layout(
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font=dict(color=effective_text_color),
xaxis=dict(
title=dict(font=dict(color=effective_text_color)),
tickfont=dict(color=effective_text_color),
gridcolor='rgba(200, 200, 200, 0.3)',
showgrid=True,
range=[-0.5, len(data['concelhos'])-0.5]
),
yaxis=dict(
title=dict(font=dict(color=effective_text_color)),
tickfont=dict(color=effective_text_color),
gridcolor='rgba(200, 200, 200, 0.3)',
showgrid=True,
autorange=True
),
legend=dict(font=dict(color=effective_text_color)),
margin=dict(l=60, r=60, b=80, t=100, pad=10),
height=600,
autosize=False
)
fig.update_layout(
legend=dict(orientation="h", yanchor="bottom", y=-0.3, xanchor="right", x=1),
title_text=f'Responses by Concelhos - {os.path.splitext(filename)[0]}' if filename and show_title else ('Responses by Concelhos' if show_title else ''),
xaxis_title='Concelhos' if show_x_label else '',
yaxis_title='Percentage' if show_y_label else '',
legend_title_text='',
legend_traceorder="normal"
)
return fig
if st.button('Preview Charts'):
for uploaded_file in uploaded_files:
data = pd.read_csv(uploaded_file)
st.write(f"Data Preview for {uploaded_file.name}:", data.head())
fig = get_fig(data, selected_chart_type, selected_palette_name, uploaded_file.name)
st.plotly_chart(fig, use_container_width=True, key=f"chart_{uploaded_file.name}")
if st.button('Export Current Chart'):
for uploaded_file in uploaded_files:
data = pd.read_csv(uploaded_file)
fig = get_fig(data, selected_chart_type, selected_palette_name, uploaded_file.name)
img_data = fig.to_image(format=export_format.lower())
st.download_button(
label=f"Download Chart as {export_format}",
data=img_data,
file_name=f"chart_{os.path.splitext(uploaded_file.name)[0]}.{export_format.lower()}",
mime=f"image/{export_format.lower()}",
key=f"download_button_{uploaded_file.name}"
)
if st.button('Export All Charts to Folder'):
progress_bar = st.progress(0)
status_text = st.empty()
try:
total_files = len(uploaded_files)
for i, uploaded_file in enumerate(uploaded_files):
# Update progress
progress = (i + 1) / total_files
progress_bar.progress(progress)
status_text.text(f"Processing file {i+1} of {total_files}: {uploaded_file.name}")
data = pd.read_csv(uploaded_file)
fig = get_fig(data, selected_chart_type, selected_palette_name, uploaded_file.name)
# Save the chart
output_path = os.path.join(output_dir, f"chart_{os.path.splitext(uploaded_file.name)[0]}.{export_format.lower()}")
print(f"Attempting to save to: {output_path}")
print(f"Directory exists: {os.path.exists(output_dir)}")
print(f"Directory writable: {os.access(output_dir, os.W_OK)}")
fig.write_image(output_path, format=export_format.lower())
print(f"File saved: {os.path.exists(output_path)}")
# Small delay to allow the file to be written
time.sleep(0.1)
status_text.text(f"Todos os {total_files} gráficos foram guardados na pasta '{os.path.basename(output_dir)}'.")
st.success(f"Exportação concluída com sucesso! Ficheiros guardados em: {os.path.abspath(output_dir)}")
except Exception as e:
status_text.text(f"Ocorreu um erro: {str(e)}")
st.error(f"Falha na exportação: {str(e)}")
import traceback
print(traceback.format_exc())
finally:
# Remove progress bar after completion
time.sleep(2)
progress_bar.empty()
status_text.empty()