Add source example files
This commit is contained in:
25
source/plotting/agg-pie.py
Normal file
25
source/plotting/agg-pie.py
Normal file
@ -0,0 +1,25 @@
|
||||
import pandas as pd
|
||||
from matplotlib import use, pyplot
|
||||
|
||||
# Utiliser tkinter
|
||||
use("TkAgg")
|
||||
pyplot.style.use('ggplot')
|
||||
pyplot.rcParams["font.family"] = "Cabin"
|
||||
|
||||
# Données à afficher
|
||||
data = pd.DataFrame(data={
|
||||
"product": ["pomme", "poire", "banane", "pêche"],
|
||||
"price": [1.99, 2.49, 2.99, 3.49]
|
||||
})
|
||||
|
||||
|
||||
def sector_label(pct: float) -> str:
|
||||
value = pct * sum(data["price"]) / 100
|
||||
return f"{value:.1f}€\n{pct:.1f}%"
|
||||
|
||||
|
||||
# Générer un graphique dans Matplotlib
|
||||
axis = data.set_index("product").plot.pie(y="price", title="Prix", autopct=sector_label)
|
||||
# Afficher le dernier graphique généré
|
||||
axis.figure.savefig("eda-matplotlib-pie-themed.png")
|
||||
pyplot.show()
|
24
source/plotting/agg-test.py
Normal file
24
source/plotting/agg-test.py
Normal file
@ -0,0 +1,24 @@
|
||||
import matplotlib
|
||||
import pandas as pd
|
||||
from matplotlib import pyplot
|
||||
from matplotlib.axes import Axes
|
||||
|
||||
matplotlib.use("TkAgg")
|
||||
pyplot.style.use('ggplot')
|
||||
pyplot.rcParams["font.family"] = "Cabin"
|
||||
|
||||
data = pd.DataFrame(data={
|
||||
"product": ["pomme", "poire", "banane", "pêche"],
|
||||
"price": [1.99, 2.49, 2.99, 3.49],
|
||||
"wpu": [200, 180, 140, 200]
|
||||
})
|
||||
# Générer un graphique dans Matplotlib
|
||||
data.plot.bar(x="product", y=["price", "wpu"], rot=0.0, secondary_y="wpu", legend="reverse", title="Prix et poids unitaires")
|
||||
prices, weights = pyplot.gcf().axes # type: Axes
|
||||
prices.legend(bbox_to_anchor=(0.0, 1.1), loc="upper left")
|
||||
weights.legend(bbox_to_anchor=(1.0, 1.1), loc="upper right")
|
||||
# Il est difficile de personnaliser le contenu du graphique
|
||||
options: dict = {"fontsize": 8, "color": "w", "rotation": 90, "label_type": "center"}
|
||||
prices.bar_label(prices.containers[0], labels=[f"{p}€" for p in data["price"]], **options)
|
||||
weights.bar_label(weights.containers[0], labels=[f"{p}g" for p in data["wpu"]], **options)
|
||||
pyplot.gcf().savefig("eda-matplotlib-bar-labeled.png")
|
BIN
source/plotting/charts/bar-chart.png
Normal file
BIN
source/plotting/charts/bar-chart.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 10 KiB |
21
source/plotting/charts/bar_chart.py
Normal file
21
source/plotting/charts/bar_chart.py
Normal file
@ -0,0 +1,21 @@
|
||||
from typing import Iterable
|
||||
|
||||
from matplotlib import pyplot as plot
|
||||
from matplotlib.axes import Axes
|
||||
from matplotlib.figure import Figure
|
||||
import matplotlib
|
||||
|
||||
if __name__ == '__main__':
|
||||
matplotlib.use("QtCairo")
|
||||
labels: Iterable[str] = ("Janvier", "Février", "Mars", "Avril")
|
||||
values: Iterable[float] = (50, 11.4, 91, 66.1)
|
||||
figure: Figure
|
||||
axis: Axes
|
||||
figure, axis = plot.subplots(nrows=1, ncols=1)
|
||||
axis.bar(x=labels, height=values, color="#00ff00")
|
||||
circle = plot.Circle((2, 20), 2, color="#FF0000", fill=False)
|
||||
axis.set_ylabel("Précipitations (mm)")
|
||||
axis.set_xlabel("Mois")
|
||||
axis.set_title("Précipitations pour 2022")
|
||||
axis.add_artist(circle)
|
||||
plot.show()
|
19
source/plotting/charts/bar_chart_save.py
Normal file
19
source/plotting/charts/bar_chart_save.py
Normal file
@ -0,0 +1,19 @@
|
||||
from typing import Iterable
|
||||
|
||||
from matplotlib import pyplot as plot
|
||||
from matplotlib.axes import Axes
|
||||
from matplotlib.figure import Figure
|
||||
import matplotlib
|
||||
|
||||
if __name__ == '__main__':
|
||||
matplotlib.use("QtCairo")
|
||||
labels: Iterable[str] = ("Janvier", "Février", "Mars", "Avril")
|
||||
values: Iterable[float] = (50, 11.4, 91, 66.1)
|
||||
figure: Figure
|
||||
axis: Axes
|
||||
figure, axis = plot.subplots(nrows=1, ncols=1)
|
||||
axis.bar(x=labels, height=values, color="#00ff00")
|
||||
axis.set_ylabel("Précipitations (mm)")
|
||||
axis.set_xlabel("Mois")
|
||||
axis.set_title("Précipitations pour 2022")
|
||||
figure.savefig("bar-chart.png", transparent=True)
|
24
source/plotting/charts/pie_chart.py
Normal file
24
source/plotting/charts/pie_chart.py
Normal file
@ -0,0 +1,24 @@
|
||||
"""
|
||||
Display sales of various cities in a sunburst chart.
|
||||
|
||||
Given the cities can have recurring parents, we can have
|
||||
a sunburst chart with 2 rings, the centermost ring for the
|
||||
country, and the outmost ring to have sales per city.
|
||||
"""
|
||||
import matplotlib
|
||||
import pandas as pd
|
||||
from matplotlib import pyplot
|
||||
|
||||
if __name__ == '__main__':
|
||||
matplotlib.use("QtCairo")
|
||||
df = pd.DataFrame(data={
|
||||
"country": ["France", "France", "Spain", "Spain"],
|
||||
"city": ["Montpellier", "Bordeaux", "Madrid", "Valencia"],
|
||||
"sales": [150_000, 127_000, 97_200, 137_250]
|
||||
})
|
||||
df.set_index(["country", "city"], inplace=True)
|
||||
total: int = df["sales"].sum()
|
||||
print(df)
|
||||
axes = df.plot.pie(subplots=True, autopct=lambda x: f"{x * total / 100:.0f} {x:.2f}%")
|
||||
pyplot.show()
|
||||
|
8
source/plotting/charts/plotly_bar.py
Normal file
8
source/plotting/charts/plotly_bar.py
Normal file
@ -0,0 +1,8 @@
|
||||
import pandas as pd
|
||||
from plotly.express import bar
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
df = pd.DataFrame(data={"label": ["Citron", "Pomme", "Mangue"], "price": [1.99, 3.97, 6.8]})
|
||||
plot = bar(df, x="label", y="price")
|
||||
plot.show()
|
11
source/plotting/charts/plotly_iris_scatter.py
Normal file
11
source/plotting/charts/plotly_iris_scatter.py
Normal file
@ -0,0 +1,11 @@
|
||||
import pandas as pd
|
||||
from plotly import express as px
|
||||
|
||||
data = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data", header=None,
|
||||
names=["sepal-length", "sepal-width", "petal-length", "petal-width", "class"])
|
||||
|
||||
plot = px.scatter(data, x="sepal-length", y="sepal-width", size="petal-width", color="class", template="seaborn",
|
||||
title="Iris flowers dataset",
|
||||
labels={"sepal-length": "Sepal length", "sepal-width": "Sepal width", "petal-width": "Petal width", "class": "Class"})
|
||||
plot.layout.update({"font": {"family": "Cabin", "size": 13}})
|
||||
plot.show()
|
21
source/plotting/charts/plotly_sunburst.py
Normal file
21
source/plotting/charts/plotly_sunburst.py
Normal file
@ -0,0 +1,21 @@
|
||||
"""
|
||||
Display sales of various cities in a sunburst chart.
|
||||
|
||||
Given the cities can have recurring parents, we can have
|
||||
a sunburst chart with 2 rings, the centermost ring for the
|
||||
country, and the outmost ring to have sales per city.
|
||||
"""
|
||||
import pandas as pd
|
||||
import plotly
|
||||
from plotly.express import sunburst
|
||||
|
||||
if __name__ == '__main__':
|
||||
df = pd.DataFrame(data={
|
||||
"country": ["France", "France", "Spain", "Spain", "England", "England", "England"],
|
||||
"city": ["Montpellier", "Bordeaux", "Madrid", "Valencia", "London", "Manchester", "Bristol"],
|
||||
"sales": [150_000, 127_000, 97_200, 137_250, 200_000, 180_000, 150_000]
|
||||
})
|
||||
plot = sunburst(df, path=["country", "city"], values="sales", title="Sales by country and city", template="ggplot2",
|
||||
color_discrete_sequence=plotly.colors.qualitative.Dark2)
|
||||
plot.layout.update({"font": {"family": "Cabin", "size": 13}})
|
||||
plot.show()
|
BIN
source/plotting/dash/france-communes.xlsx
Normal file
BIN
source/plotting/dash/france-communes.xlsx
Normal file
Binary file not shown.
24
source/plotting/dash/simple_dashboard.py
Normal file
24
source/plotting/dash/simple_dashboard.py
Normal file
@ -0,0 +1,24 @@
|
||||
import dash
|
||||
import pandas as pd
|
||||
from dash import Dash, html, dash_table, dcc
|
||||
from plotly.express import line
|
||||
|
||||
|
||||
data = pd.read_excel("france-communes.xlsx")
|
||||
dept = data.groupby("departement").sum("population")
|
||||
app = Dash("demo")
|
||||
app.layout = html.Div(children=[
|
||||
html.H1(children="Dashboard"),
|
||||
dash_table.DataTable(data=data.to_dict("records"), page_size=10),
|
||||
dcc.Graph(id="dept-population", figure=line(dept, x=None, y="population")),
|
||||
dcc.Dropdown(id="color-select", options=["#ff0000", "#00ff00"])
|
||||
])
|
||||
|
||||
|
||||
@app.callback(dash.Output("dept-population", "figure"), dash.Input("color-select", "value"))
|
||||
def update_dept_population(color):
|
||||
return line(dept, x=None, y="population", color_discrete_sequence=[color])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
BIN
source/plotting/eda-matplotlib-bar-labeled.png
Normal file
BIN
source/plotting/eda-matplotlib-bar-labeled.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 26 KiB |
BIN
source/plotting/eda-matplotlib-bar-themed.png
Normal file
BIN
source/plotting/eda-matplotlib-bar-themed.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 17 KiB |
BIN
source/plotting/eda-matplotlib-pie-themed.png
Normal file
BIN
source/plotting/eda-matplotlib-pie-themed.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 27 KiB |
45
source/plotting/gui/base-window.ui
Normal file
45
source/plotting/gui/base-window.ui
Normal file
@ -0,0 +1,45 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>MainWindow</class>
|
||||
<widget class="QMainWindow" name="MainWindow">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>600</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>MainWindow</string>
|
||||
</property>
|
||||
<widget class="QWidget" name="centralwidget">
|
||||
<layout class="QVBoxLayout" name="verticalLayout">
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="horizontalLayout">
|
||||
<item>
|
||||
<widget class="QPushButton" name="refresh_button">
|
||||
<property name="text">
|
||||
<string>Refresh</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QMenuBar" name="menubar">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>34</height>
|
||||
</rect>
|
||||
</property>
|
||||
</widget>
|
||||
<widget class="QStatusBar" name="statusbar"/>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
63
source/plotting/gui/base_graph.py
Normal file
63
source/plotting/gui/base_graph.py
Normal file
@ -0,0 +1,63 @@
|
||||
import pandas as pd
|
||||
from PySide6.QtCore import QObject, Slot
|
||||
from PySide6.QtUiTools import QUiLoader
|
||||
from PySide6.QtWidgets import QWidget, QMainWindow, QApplication, QPushButton
|
||||
from matplotlib.axes import Axes
|
||||
from matplotlib.backends.backend_qt import FigureCanvasQT
|
||||
from matplotlib.backends.backend_qtcairo import FigureCanvasQTCairo
|
||||
from matplotlib.figure import Figure
|
||||
|
||||
|
||||
class Main(QObject):
|
||||
"""Classe de gestion d'affichage de diagramme dans pyside."""
|
||||
area: QWidget = None
|
||||
window: QMainWindow | QWidget = None
|
||||
canvas: FigureCanvasQT = None
|
||||
refresh_button: QPushButton = None
|
||||
plot1: Axes = None
|
||||
data = pd.DataFrame({"age": [25, 45, 65], "prenom": ["Pierre", "Paul", "Jacques"]})
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.window = QUiLoader().load("base-window.ui")
|
||||
self.area = self.window.centralWidget()
|
||||
self.refresh_button = self.window.refresh_button
|
||||
# Créer un canevas compatible avec Matplotlib
|
||||
self.canvas = FigureCanvasQTCairo()
|
||||
self.canvas.figure = self.create_figures()
|
||||
self.area.layout().addWidget(self.canvas)
|
||||
self.show_bar()
|
||||
# Répondre à un événement sur le bouton
|
||||
self.refresh_button.clicked.connect(self.on_refresh_button_click)
|
||||
|
||||
@Slot()
|
||||
def on_refresh_button_click(self):
|
||||
"""Rafraîchir le graphique."""
|
||||
self.show_line()
|
||||
self.canvas.draw()
|
||||
|
||||
def create_figures(self) -> Figure:
|
||||
"""Générer une image avec un graphique."""
|
||||
figure = Figure(dpi=96)
|
||||
self.plot1 = figure.add_subplot(111) # 1 colonne, 1 ligne, position 1
|
||||
return figure
|
||||
|
||||
def show_bar(self):
|
||||
"""Mettre à jour le canevas avec un diagramme en barres."""
|
||||
self.canvas.figure.clear() # retirer tous les graphiques
|
||||
self.plot1 = self.canvas.figure.add_subplot(111) # 1 colonne, 1 ligne, position 1
|
||||
self.data.plot.bar(x="prenom", y="age", ax=self.plot1, rot=0)
|
||||
|
||||
def show_line(self):
|
||||
"""Mettre à jour le canevas avec un diagramme en lignes."""
|
||||
self.canvas.figure.clear() # retirer tous les graphiques
|
||||
self.plot1 = self.canvas.figure.add_subplot(111) # 1 colonne, 1 ligne, position 1
|
||||
self.data.plot.line(x="prenom", y="age", ax=self.plot1, color="#ffa820")
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
application = QApplication()
|
||||
main = Main()
|
||||
main.window.show()
|
||||
application.exec()
|
44
source/plotting/gui/quick_threading.py
Normal file
44
source/plotting/gui/quick_threading.py
Normal file
@ -0,0 +1,44 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from PySide6.QtCore import QObject, Slot, QThreadPool
|
||||
from PySide6.QtUiTools import QUiLoader
|
||||
from PySide6.QtWidgets import QWidget, QMainWindow, QApplication, QPushButton
|
||||
|
||||
|
||||
class Main(QObject):
|
||||
"""Classe de gestion de threads dans Pyside."""
|
||||
area: QWidget = None
|
||||
window: QMainWindow | QWidget = None
|
||||
refresh_button: QPushButton = None
|
||||
thread_pool = QThreadPool()
|
||||
counter: int = 0
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.window = QUiLoader().load("base-window.ui")
|
||||
self.area = self.window.centralWidget()
|
||||
self.refresh_button = self.window.refresh_button
|
||||
# Répondre à un événement sur le bouton
|
||||
self.refresh_button.clicked.connect(self.on_refresh_button_click)
|
||||
|
||||
@Slot()
|
||||
def on_refresh_button_click(self):
|
||||
"""Rafraîchir le graphique."""
|
||||
self.refresh_button.setDisabled(True)
|
||||
self.thread_pool.start(self.counter_updater)
|
||||
|
||||
def counter_updater(self):
|
||||
"""Thread."""
|
||||
while True:
|
||||
self.counter += 1
|
||||
self.refresh_button.setText(f"{self.counter}")
|
||||
time.sleep(1.0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
application = QApplication()
|
||||
main = Main()
|
||||
main.window.show()
|
||||
application.exec()
|
12
source/plotting/plotly-bar-series.py
Normal file
12
source/plotting/plotly-bar-series.py
Normal file
@ -0,0 +1,12 @@
|
||||
import pandas as pd
|
||||
from plotly import express
|
||||
|
||||
|
||||
values = pd.Series(
|
||||
data=[1.99, 2.49, 2.99, 3.49],
|
||||
index=["pomme", "poire", "banane", "peche"],
|
||||
name="price"
|
||||
)
|
||||
# Générer un graphique
|
||||
figure = express.bar(values, x=None, y="price")
|
||||
figure.show()
|
10
source/plotting/plotly-barcolors.py
Normal file
10
source/plotting/plotly-barcolors.py
Normal file
@ -0,0 +1,10 @@
|
||||
import pandas as pd
|
||||
from plotly import express as px
|
||||
|
||||
data = pd.DataFrame(data={
|
||||
"product": ["pomme", "poire", "banane", "pêche"],
|
||||
"price": [1.99, 2.49, 2.99, 3.49], "wpu": [200, 180, 140, 200]
|
||||
})
|
||||
figure = px.bar(data, y="price", x="product", title="Prix", color="price", color_continuous_scale=["red", "orange", "yellow", "#8F0"])
|
||||
figure.layout.update({"template": "seaborn", "title": "Prix au kilo", "font": {"family": "Cabin", "size": 13}})
|
||||
figure.show()
|
18
source/plotting/plotly-compose.py
Normal file
18
source/plotting/plotly-compose.py
Normal file
@ -0,0 +1,18 @@
|
||||
import pandas as pd
|
||||
from plotly.graph_objs import Figure, Bar
|
||||
|
||||
data = pd.DataFrame(data={
|
||||
"product": ["pomme", "poire", "banane", "pêche"],
|
||||
"price": [1.99, 2.49, 2.99, 3.49], "wpu": [200, 180, 140, 200]
|
||||
})
|
||||
figure = Figure([
|
||||
Bar(name="Prix", x=data["product"], y=data["price"], yaxis="y", offsetgroup=1),
|
||||
Bar(name="Poids", x=data["product"], y=data["wpu"], yaxis="y2", offsetgroup=2),
|
||||
])
|
||||
# Afficher le dernier graphique généré
|
||||
figure.layout.update({
|
||||
"template": "seaborn",
|
||||
"title": "Prix et poids unitaires", "font": {"family": "Cabin", "size": 13},
|
||||
"yaxis": {"title": "Prix (€)"}, "yaxis2": {"title": "Poids (g)", "overlaying": "y", "side": "right"}
|
||||
})
|
||||
figure.show()
|
10
source/plotting/plotly-piecolors.py
Normal file
10
source/plotting/plotly-piecolors.py
Normal file
@ -0,0 +1,10 @@
|
||||
import pandas as pd
|
||||
from plotly import express as px
|
||||
|
||||
data = pd.DataFrame(data={
|
||||
"product": ["pomme", "poire", "banane", "pêche"],
|
||||
"price": [1.99, 2.49, 2.99, 3.49], "wpu": [200, 180, 140, 200]
|
||||
})
|
||||
figure = px.pie(data, values="price", names="product", title="Prix", color_discrete_sequence=["red", "orange", "yellow", "#8F0"])
|
||||
figure.layout.update({"template": "seaborn", "title": "Prix au kilo", "font": {"family": "Cabin", "size": 13}})
|
||||
figure.show()
|
15
source/plotting/plotly-pielabel.py
Normal file
15
source/plotting/plotly-pielabel.py
Normal file
@ -0,0 +1,15 @@
|
||||
import pandas as pd
|
||||
from plotly import express as px
|
||||
|
||||
data = pd.DataFrame(data={
|
||||
"product": ["pomme", "poire", "banane", "pêche"],
|
||||
"price": [1.99, 2.49, 2.99, 3.49], "wpu": [200, 180, 140, 200]
|
||||
})
|
||||
figure = px.pie(data, values="price", names="product", title="Prix")
|
||||
# Afficher le dernier graphique généré
|
||||
figure.layout.update({
|
||||
"template": "seaborn",
|
||||
"title": "Prix au kilo", "font": {"family": "Cabin", "size": 13},
|
||||
})
|
||||
figure.update_traces(**{"textinfo": "label+value", "texttemplate": "%{label}<br>%{value:.2f}€"})
|
||||
figure.show()
|
13
source/plotting/plotly-test.py
Normal file
13
source/plotting/plotly-test.py
Normal file
@ -0,0 +1,13 @@
|
||||
import pandas as pd
|
||||
from plotly import express
|
||||
|
||||
data = pd.DataFrame(data={
|
||||
"product": ["pomme", "poire", "banane", "pêche"],
|
||||
"price": [1.99, 2.49, 2.99, 3.49],
|
||||
"wpu": [200, 180, 140, 200]
|
||||
})
|
||||
# Générer un graphique. Plotly express ne prend en charge qu'un seul graphique par figure
|
||||
figure = express.bar(data, x="product", y="price", title="Prix", template="seaborn",
|
||||
labels={"price": "Prix", "product": "Produit"})
|
||||
figure.layout.update({"font": {"family": "Cabin", "size": 13}})
|
||||
figure.show()
|
Reference in New Issue
Block a user