Code Monkey home page Code Monkey logo

pec2_visualization's Introduction

PEC 2

Javier Advani

Descripción y enunciado

En esta actividad el estudiante tendrá que crear tres pequeñas visualizaciones usando técnicas diferentes que le serán asignadas, recibiréis un correo de vuestro profesor con la selección. Cada estudiante tendrá que escoger unos datos idóneos para cada una de las técnicas propuestas y decidir con qué software las crea. Los datos se podrán escoger de cualquier fuente de datos abiertos. El estudiante publicará las representaciones a Internet y las presentará en un video. El video deberá subirse a la zona llamada VideoPAC del aula.

Para publicar las representaciones os recordamos que hace falta que estas sean accesibles directamente con una URL, sin necesidad de registros ni inicios de sesión. Esto tanto se puede hacer en la misma plataforma donde se ha desarrollado la representación (Flourish, Tableau Public, Infogram, etc), como en un espacio gratuito como por ejemplo github, donde podéis crear un proyecto y publicar las representaciones en formato web a github.io, por ejemplo.(How to github.io)

Se trata de familiarizarse con técnicas de visualización y entender la esencia. De hecho, en lugar de ir de los datos a la visualización, en esta actividad lo hacemos a la inversa, es decir, a partir de cada técnica tenemos que ver para qué tipo de datos es adecuada y buscar un conjunto de datos que sea coherente, si puede ser sin tener que hacer ninguna transformación en los datos (para ahorraros trabajo).

A esta actividad hay que publicar las tres técnicas y un video explicativo que sigue el guión siguiente:

[Puntos 1 y 2] Presentaros siguiendo el esquema de la PEC 1.
[Puntos 1 y 2: 5%] Indicad donde está colgada la visualización y cómo acceder.
[Punto 3: 30%] Definid cada técnica de visualización de forma general: nombre, origen, descripción/funcionamiento, ejemplos de aplicación, etc.
[Punto 4: 10%] Describid el tipo de datos que se pueden representar con cada técnica (datos cuantitativos, cualitativas? Qué estructura tienen que tener para cada técnica?). Explicar las limitaciones en cuanto a datos (hay medida mínima y máxima del juego de datos para cada técnica?).
[Punto 5: 20%] Hacer una representación con cada una de las técnicas usando un conjunto de datos abiertos (veáis más abajo algunas fuentes de datos abiertos). En total hay que hacer 3 representaciones simples con 3 conjuntos de datos escogidos por el estudiante.
[Punto 6: 30%] Comentar brevemente las tres representaciones indicando qué se representa y qué o qué aspectos muestra o demuestra cada representación.
[Punto 7: 5%] Cada una de las tres presentaciones deben tener una duración de unos 2-3 minutos. En total, el vídeo (único) con las tres técnicas no puede exceder de 7 minutos. Se penalizará salir de ese rango, porque se valora la capacidad de síntesis y de comunicación

Algunas fuentes de datos abiertos:

  1. COVID:

Europa: https://www.ecdc.europa.eu/en/covid-19/data Cataluña: https://analisi.transparenciacatalunya.cat/es/browse?q=covid&sortby=relevance España: https://datos.gob.es/en/catalogo?q=covid&theme_id=salud&sort=metadata_created+desc

2)Portales Open Data :

CAT: http://governobert.gencat.cat/ca/dades_obertes/ ES: https://datos.gob.es/ UK: https://data.gov.uk/ USA: https://www.data.gov/ AVE: https://data.gov.au/data

  1. Otros:

Data Sonification: https://sonification.design/ RAW: https://app.rawgraphs.io/ -> Acceso a los datasets: https://github.com/rawgraphs/rawgraphs-app/tree/master/public/sample-datasets PAX: https://www.peaceagreements.org/ Information is beutiful: https://informationisbeautiful.net/data/ Kaggle: https://www.kaggle.com/datasets Directorio de datasets: https://www.dataquest.io/blog/free-datasets-for-projects/ Google dataset search: https://datasetsearch.research.google.com/ Gapminder: https://www.gapminder.org/data/

Recordad que en la Biblioteca también tenéis acceso al recurso Statista y en el espacio de recursos de ciencia de datos de la UOC también podréis encontrar otras fuentes de datos:

https://datascience.recursos.uoc.edu/?filter=.cdades

NOTA: Sobre los requisitos técnicos del vídeo para la entrega en VideoPAC: la herramienta soporta un tamaño máximo de 2GB y se pueden subir en cualquier formato, pero os recomendamos que uséis mp4 en resoluciones múltiplos de 360 (720, 1080…), para evitar problemas de transcodificación en la plataforma.

1. Bar Chart

A Bar graph is used when you want to show a distribution of categorical variables or ordinal subgroups of your data. From a bar chart, we can see which groups are highest or most common, and how other groups compare against the others.

import pandas as pd
# fuente: https://www.kaggle.com/datasets/ashydv/housing-dataset/code
df = pd.read_csv('Housing.csv')
df.head()
<style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; }
.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}
</style>
price area bedrooms bathrooms stories mainroad guestroom basement hotwaterheating airconditioning parking prefarea furnishingstatus
0 13300000 7420 4 2 3 yes no no no yes 2 yes furnished
1 12250000 8960 4 4 4 yes no no no yes 3 no furnished
2 12250000 9960 3 2 2 yes no yes no no 2 yes semi-furnished
3 12215000 7500 4 2 2 yes no yes no yes 3 yes furnished
4 11410000 7420 4 1 2 yes yes yes no yes 2 no furnished
# Bar chart

import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="darkgrid")
total = float(len(df))
ax = sns.countplot(x="bedrooms", data=df)
for p in ax.patches:
    percentage = '{:.1f}%'.format(100 * p.get_height()/total)
    x = p.get_x() + p.get_width()
    y = p.get_height()
    ax.annotate(percentage, (x, y),ha='center')
ax.set(title="Number of Bedrooms in Houses", ylabel="%", xlabel= "nº bedrooms")
plt.show()

png

2. Small Multiple

A Small Multiple is a data visualization that consists of multiple charts arranged in a grid. This makes it easy to compare the entirety of the data.

# Small Multiple
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
df=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14), 'y9': np.random.randn(10)+range(4,14) })
palette = plt.get_cmap('Set1')
num=0
for column in df.drop('x', axis=1):
    num+=1
    plt.subplot(3,3, num)
    plt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=1.9, alpha=0.9, label=column)
 
    # Same limits for every chart
    plt.xlim(0,10)
    plt.ylim(-2,22)
 
    # Not ticks everywhere
    if num in range(7) :
        plt.tick_params(labelbottom='off')
    if num not in [1,4,7] :
        plt.tick_params(labelleft='off')
 
    # Add title
    plt.title(column, loc='left', fontsize=12, fontweight=0, color=palette(num) )

# general title
plt.suptitle("How top 9 cryptos evolved\nthese past few days?", fontsize=13, fontweight=0, color='black', style='italic', y=1.02)
 
# Axis titles
plt.text(0.5, 0.02, 'Time', ha='center', va='center')
plt.text(0.06, 0.5, 'Note', ha='center', va='center', rotation='vertical')

# Show the graph
plt.show()

png

3. Chord Diagram

The Chord element allows representing the inter-relationships between data points in a graph. The nodes are arranged radially around a circle with the relationships between the data points drawn as arcs (or chords) connecting the nodes. The number of chords is scaled by a weight declared as a value dimension on the Chord element.

If the weight values are integers, they define the number of chords to be drawn between the source and target nodes directly. If the weights are floating point values, they are normalized to a default of 500 chords, which are divided up among the edges. Any non-zero weight will be assigned at least one chord.

The Chord element is a type of Graph element and shares the same constructor. The most basic constructor accepts a columnar dataset of the source and target nodes and an optional value. Here we supply a dataframe containing the number of dialogues between characters of the Les Misérables musical. The data contains source and target node indices and an associated value column:

import pandas as pd
import holoviews as hv
from holoviews import opts, dim
from bokeh.sampledata.les_mis import data

hv.extension('bokeh')
hv.output(size=200)
<style>.bk-root, .bk-root .bk:before, .bk-root .bk:after { font-family: var(--jp-ui-font-size1); font-size: var(--jp-ui-font-size1); color: var(--jp-ui-font-color1); } </style>

links = pd.DataFrame(data['links'])
print(links.head(3))
   source  target  value
0       1       0      1
1       2       0      8
2       3       0     10

In the simplest case we can construct the Chord by passing it just the edges

hv.Chord(links)

png

The plot automatically adds hover and tap support, letting us reveal the connections of each node.

To add node labels and other information we can construct a Dataset with a key dimension of node indices.

Additionally we can now color the nodes and edges by their index and add some labels. The labels, node_color and edge_color options allow us to reference dimension values by name.

source: https://holoviews.org/reference/elements/bokeh/Chord.html

pec2_visualization's People

Contributors

jadvani avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.