I'm working on this project where I've got some dataframes and plots. I've got the plots all sorted out, but now I'm trying to figure out how to show the tabular dataframes and maybe add a download button for them. I can't decide if I should bundle them in a zip file or give each one a separate download button. I tried using Panel, but it's kinda slow, and the Python script examples I found aren't working for me. Another idea I had was to save the dataframes as JSON and use some JavaScript magic, but I'm not really a JavaScript pro like I am with Python. If you've got any thoughts, advice, or maybe even some code examples to help me out, I'd really appreciate it.
Here is my code if it's needed:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
</head>
<body>
<py-config>
packages = ['pandas', 'matplotlib', 'numpy']
</py-config>
<div class="container">
<h1>Resultados del Test</h1>
<!--Script Python-->
<py-script>
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from js import location, URLSearchParams
import json
urlParams = URLSearchParams.new(location.search)
userDataJSON = urlParams.get('respuestas')
userData = json.loads(userDataJSON)
electricity_data = userData["electricityResponses"]["records"]
df_electricity = pd.DataFrame(electricity_data)
df_electricity = df_electricity.rename(columns={"receiptNumber": "receipt", "kWhConsumption":
"consume_kwh"})
df_electricity["consume_mwh"] = df_electricity["consume_kwh"] / 1000
emissionFactorElectrity = 0.435
df_electricity["emission_tco2"] = df_electricity["consume_mwh"] * emissionFactorElectrity
emissionResultElectricity = df_electricity["consume_mwh"].sum() * emissionFactorElectrity
plt.plot(df_electricity["receipt"], df_electricity["consume_mwh"])
plt.title("Consumo anual de electricidad")
plt.xlabel("No. de recibo bimestral")
plt.ylabel("Consumo bimestral de electricidad (MWh)")
display(plt)
plt.clf()
plt.bar(df_electricity["receipt"], df_electricity["emission_tco2"])
plt.title("Emisión de carbono anual de electricidad")
plt.xlabel("Consumo de electricidad bimestral (MWh)")
plt.ylabel("Emisión bimestral de carbono (tco2)")
display(plt)
water_data = userData["waterResponses"]["records"]
df_water = pd.DataFrame(water_data)
df_water = df_water.rename(columns={"receiptNumber": "receipt", "m3Consumption": "consume_m3"})
emissionFactorWater = 0.26 / 1000
df_water["emission_tco2"] = df_water["consume_m3"] * emissionFactorWater
emissionResultWater = df_water["consume_m3"].sum() * emissionFactorWater
plt.clf()
plt.plot(df_water["receipt"], df_water["consume_m3"])
plt.title("Consumo anual de agua")
plt.xlabel("No. de recibo bimestral")
plt.ylabel("Consumo bimestral de agua (m^3)")
display(plt)
plt.clf()
plt.bar(df_water["receipt"], df_water["emission_tco2"])
plt.title("Emisión de carbono anual de agua")
plt.xlabel("Consumo de agua bimestral (m^3)")
plt.ylabel("Emisión bimestral de carbono (tco2)")
display(plt)
gas_data = userData["gasResponses"]
df_gas = pd.DataFrame([gas_data])
df_gas = df_gas.rename(columns={"naturalGasConsumption": "consume_natural_gas", "LPGConsumption":
"consume_lp_gas"})
emissionFactorNaturalGas = 2.2161 / 1000
emissionFactorLPGas = 2.5868 / 1000
df_gas["emission_tco2_natural_gas"] = df_gas["consume_natural_gas"] * emissionFactorNaturalGas
emissionResultNaturalGas = df_gas["consume_natural_gas"].sum() * emissionFactorNaturalGas
df_gas["emission_tco2_lp_gas"] = df_gas["consume_lp_gas"] * emissionFactorLPGas
emissionResultLPGas = df_gas["consume_lp_gas"].sum() * emissionFactorLPGas
lblsGas = ["Gas Natural", "Gas LP"]
plt.clf()
gasVals = list(df_gas["consume_natural_gas"]) + list(df_gas["consume_lp_gas"])
plt.pie(gasVals, labels=lblsGas, autopct="%1.1f%%")
plt.title("Consumo anual de gas")
display(plt)
plt.clf()
gasEmissionVals = list(df_gas["emission_tco2_natural_gas"]) + list(df_gas["emission_tco2_lp_gas"])
plt.bar(lblsGas, gasEmissionVals)
plt.title("Emisión de carbono anual de gas")
plt.xlabel("Tipo de gas")
plt.ylabel("Emisión de carbono (tco2)")
display(plt)
transport_data = userData["transportResponses"]["vehicles"]
df_transport = pd.DataFrame(transport_data)
df_transport["isDiesel"] = df_transport["isDiesel"].map({"true":True, "false":False})
emissionFactorFuel = 2.953 / 1000
emissionFactorDiesel = 3.1034 / 1000
def calculate_emission(row):
if not row["isDiesel"]:
return row["kmsDriven"] * row["efficiency"] * emissionFactorFuel
else:
return row["kmsDriven"] * row["efficiency"] * emissionFactorDiesel
df_transport["emission_tco2"] = df_transport.apply(calculate_emission, axis=1)
emissionResultTransport = df_transport["emission_tco2"].sum()
plt.clf()
lblsTransport = [i for i in range(1, len(df_transport["noVehicle"])+1)]
plt.bar(lblsTransport, df_transport["emission_tco2"])
plt.title("Emisión de carbono anual de transporte")
plt.xticks(lblsTransport)
plt.xlabel("Carros")
plt.ylabel("Emisión de carbono (tco2)")
display(plt)
plt.clf()
emissionResults = [emissionResultElectricity, emissionResultNaturalGas, emissionResultLPGas,
emissionResultWater, emissionResultTransport]
lblsResults = ["Electricidad", "Gas Natural", "Gas LP", "Agua", "Transporte"]
plt.figure(figsize=(10,10))
plt.pie(emissionResults, labels=lblsResults, autopct="%1.1f%%")
plt.title("Emisiones de carbono")
display(plt)
</py-script>
<div id="electricityFactorResult"></div>
<br>
<div id="waterFactorResult"></div>
<br>
<div id="gasFactorResult"></div>
<br>
<div id="transportFactorResult"></div>
</div>
</body>
</html>