-
Goal: I´m triying add a chart in html component
-
Steps:
-
Load with a CDN the Plotyjs library
-
I add the next code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gráfico de Barras con Proporciones</title>
</head>
<body>
<h3>Grafico</h3>
<div id="chart"></div>
<script>
// Datos de las transacciones
const data = [
{ "Comercio": "Innovasport", "Precio": 100 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Starbucks", "Precio": 80 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Cinemex", "Precio": 50 },
{ "Comercio": "Krispy Kreme", "Precio": 205 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Amazon", "Precio": 100 },
{ "Comercio": "Starbucks", "Precio": 80 },
{ "Comercio": "Amazon Prime Video", "Precio": 97 },
{ "Comercio": "Librerías Ghandi", "Precio": 150 },
];
// Agrupar y contar transacciones por comercio
const groupedData = data.reduce((acc, curr) => {
acc[curr.Comercio] = (acc[curr.Comercio] || 0) + 1;
return acc;
}, {});
const totalRegistros = data.length;
const comercios = Object.keys(groupedData);
const proporciones = Object.values(groupedData).map(count => count / totalRegistros);
// Configuración del gráfico
const trace = {
x: comercios,
y: proporciones,
type: 'bar',
marker: {
color: 'rgba(58,71,80,0.8)'
},
text: proporciones.map(p => (p * 100).toFixed(2) + '%'), // Mostrar porcentajes como etiquetas
textposition: 'auto'
};
const layout = {
title: 'Proporción de Transacciones por Comercio',
xaxis: {
title: 'Comercio'
},
yaxis: {
title: 'Proporción',
tickformat: ',.0%' // Formato de porcentaje
}
};
// Renderizar el gráfico
Plotly.newPlot('chart', [trace], layout);
</script>
</body>
</html>
- Details: The chart is not visible, just don´t shows