Spaces:
Sleeping
Sleeping
File size: 7,548 Bytes
4eafb07 11b9056 4eafb07 11b9056 facb61e 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 11b9056 4eafb07 |
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 |
from pandas import DataFrame
from plotly.subplots import make_subplots
from plotly.graph_objects import Figure, Pie, Bar, Scatter, Scatterpolar
def draw_report_figure(
df: DataFrame, threshold: tuple[float] = [15_000, 5_000, 15_000]
) -> Figure:
figure_specs = [
[{"type": "xy"}, {"type": "domain"}],
[{"type": "xy"}, {"type": "xy"}],
]
fig = make_subplots(
rows=2,
cols=2,
specs=figure_specs,
subplot_titles=(
"Carbon Emission by Category",
"Emission Distribution",
),
)
# Pie chart settings
pie_pull = [0.15 if x == min(df["Value"]) else 0.0 for x in df["Value"]]
fig.add_trace(
Pie(
values=df["Value"],
labels=df["Category"],
hole=0.3,
pull=pie_pull,
name="Emission Distribution",
marker={"colors": ["#6DA34D", "#81C3D7", "#FFC857"]},
),
row=1,
col=2,
)
# Bar chart for emissions by category
fig.add_trace(
Bar(
x=df["Category"],
y=df["Value"],
name="Carbon Emission (kgCO2)",
marker_color=["#6DA34D", "#81C3D7", "#FFC857"],
),
row=1,
col=1,
)
# Annotation for highest emission
fig.add_annotation(
x=df["Category"][df["Value"].idxmax()],
y=df["Value"].max(),
text="Highest Emission",
showarrow=True,
arrowhead=1,
ax=0,
ay=-40,
row=1,
col=1,
)
# Update layout for axes and overall layout
fig.update_layout(
title_text=f"Carbon Footprint of {df['Name'][0]}",
plot_bgcolor="white",
legend_title_text="Breakdown",
xaxis_title="Emission Category",
yaxis_title="Carbon Emission (kgCO2)",
yaxis=dict(
linecolor="black",
showline=True,
ticks="outside",
mirror=True,
gridcolor="lightgrey",
),
legend=dict(
x=1,
y=0,
xanchor="right",
yanchor="bottom",
orientation="h",
),
)
fig.update_xaxes(
linecolor="black",
ticks="outside",
showline=True,
mirror=True,
)
fig.update_yaxes(
linecolor="black",
showline=True,
ticks="outside",
mirror=True,
gridcolor="lightgrey",
)
# Add a single general recommendation text box
e, w, b = df["Value"]
threshold_values = [e >= threshold[0], w >= threshold[1], b >= threshold[2]]
recommendations = []
texts = [
"- Reduce energy usage by adopting energy-efficient practices.\n",
"- Minimize waste by recycling and using sustainable materials.\n",
"- Limit business travel and opt for virtual meetings where possible."
]
if any(threshold_values):
fig.add_annotation(
text=("Recommendations to reduce carbon footprint:\n"),
xref="paper",
yref="paper",
x=0,
y=0.2, # Positioning inside the plot area, just below center
showarrow=False,
font=dict(size=12),
align="center",
bordercolor="black",
borderwidth=1,
borderpad=10,
bgcolor="lightyellow",
)
if threshold_values[0]:
recommendations.append(texts[0])
if threshold_values[1]:
recommendations.append(texts[1])
if threshold_values[2]:
recommendations.append(texts[2])
for i, text in enumerate(recommendations):
fig.add_annotation(
text=(text),
xref="paper",
yref="paper",
x=0,
y=(i + 1) * 0.05, # Positioning inside the plot area, just below center
showarrow=False,
font=dict(size=12),
align="center",
bordercolor="black",
borderwidth=1,
borderpad=10,
bgcolor="lightyellow",
)
return fig
def draw_historic_figure(df: DataFrame) -> Figure:
# Create subplots with 2 rows and 1 column
fig = make_subplots(
rows=2,
cols=1,
specs=[[{"type": "xy"}], [{"type": "polar"}]],
subplot_titles=(
"Total Carbon Footprint by Company",
"Company Metrics Radar Chart",
),
row_heights=[0.6, 0.4],
)
# Calculate each company's total carbon footprint as the sum of the three metrics
df["Carbon Footprint"] = (
df["Energy Usage"] + df["Waste Generated"] + df["Business Travel"]
)
# Add gradient-filled area trace for the Carbon Footprint
fig.add_trace(
Scatter(
x=df["Name"],
y=df["Carbon Footprint"],
mode="lines",
fill="tozeroy",
line=dict(color="blue"),
fillcolor="rgba(31, 119, 180, 0.5)", # Gradient fill for blue
name="Carbon Footprint",
),
row=1,
col=1,
)
# Prepare data for radar chart (normalizing values for better comparability)
categories = ["Energy Usage", "Waste Generated", "Business Travel"]
for _, company in df.iterrows():
fig.add_trace(
Scatterpolar(
r=[
company["Energy Usage"],
company["Waste Generated"],
company["Business Travel"],
company["Energy Usage"], # Closing the loop
],
theta=categories + [categories[0]], # Circular radar plot
fill="toself",
name=company["Name"],
),
row=2,
col=1,
)
# Update layout for the figure
fig.update_layout(
title="Company Metrics Visualization",
template="plotly_white",
height=800,
width=1000,
showlegend=True,
legend=dict(x=1.05, y=1), # Adjust legend position
)
# Update x and y-axis titles for the first plot
fig.update_xaxes(title_text="Company", row=1, col=1)
fig.update_yaxes(title_text="Carbon Footprint (total)", row=1, col=1)
# Customize polar (radar) chart layout
fig.update_polars(
radialaxis=dict(
visible=True,
range=[
df[categories].values.min(),
df[categories].values.max(),
],
)
)
return fig
def make_dataframe(
company_name: str,
avg_electric_bill: float,
avg_gas_bill: float,
avg_transport_bill: float,
monthly_waste_generated: float,
recycled_waste_percent: float,
annual_travel_kms: float,
fuel_efficiency: float,
) -> DataFrame:
energy_usage = (
(avg_electric_bill * 12 * 5e-4)
+ (avg_gas_bill * 12 * 5.3e-3)
+ (avg_transport_bill * 12 * 2.32)
)
waste_generated = monthly_waste_generated * 12 * 0.57 - recycled_waste_percent
business_travel = annual_travel_kms * 1 / fuel_efficiency * 2.31
return DataFrame(
{
"Name": company_name,
"Category": ["Energy Usage", "Waste Generated", "Business Travel"],
"Value": [energy_usage, waste_generated, business_travel],
}
)
def dataframe_to_dict(df: DataFrame) -> dict:
return {
"Name": df["Name"][0],
"Energy Usage": df["Value"][0],
"Waste Generated": df["Value"][1],
"Business Travel": df["Value"][2],
}
|