-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotnine.py
More file actions
105 lines (96 loc) · 2.75 KB
/
plotnine.py
File metadata and controls
105 lines (96 loc) · 2.75 KB
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
""" anyplot.ai
slope-basic: Basic Slope Chart (Slopegraph)
Library: plotnine 0.15.3 | Python 3.13.13
Quality: 80/100 | Updated: 2026-04-30
"""
import pandas as pd
from plotnine import (
aes,
element_blank,
element_text,
geom_line,
geom_point,
geom_text,
ggplot,
labs,
scale_color_manual,
scale_x_continuous,
theme,
theme_minimal,
)
# Data: Quarterly sales figures (in thousands) comparing Q1 vs Q4
entities = [
"Product A",
"Product B",
"Product C",
"Product D",
"Product E",
"Product F",
"Product G",
"Product H",
"Product I",
"Product J",
]
q1_sales = [120, 85, 200, 150, 95, 175, 110, 140, 65, 180]
q4_sales = [165, 70, 230, 135, 145, 190, 85, 160, 110, 155]
# Calculate change direction for color coding
changes = ["Increase" if q4 >= q1 else "Decrease" for q1, q4 in zip(q1_sales, q4_sales, strict=True)]
# Create long-format DataFrame for lines
df_long = pd.DataFrame(
{
"entity": entities * 2,
"x": [1] * len(entities) + [2] * len(entities),
"value": q1_sales + q4_sales,
"change": changes * 2,
}
)
# Create label DataFrames
df_labels_left = pd.DataFrame(
{
"entity": entities,
"x": [1] * len(entities),
"value": q1_sales,
"change": changes,
"label": [f"{e} ({v})" for e, v in zip(entities, q1_sales, strict=True)],
}
)
df_labels_right = pd.DataFrame(
{
"entity": entities,
"x": [2] * len(entities),
"value": q4_sales,
"change": changes,
"label": [str(v) for v in q4_sales],
}
)
# Plot
plot = (
ggplot(df_long, aes(x="x", y="value", group="entity", color="change"))
+ geom_line(size=1.5, alpha=0.8)
+ geom_point(size=5)
# Left labels (entity name + value)
+ geom_text(aes(label="label"), data=df_labels_left, ha="right", nudge_x=-0.08, size=10)
# Right labels (value only)
+ geom_text(aes(label="label"), data=df_labels_right, ha="left", nudge_x=0.08, size=10)
+ scale_color_manual(values={"Increase": "#306998", "Decrease": "#FFD43B"})
+ scale_x_continuous(breaks=[1, 2], labels=["Q1", "Q4"], limits=(0.3, 2.7))
+ labs(
x="",
y="Sales (thousands $)",
title="Product Sales Q1 vs Q4 · slope-basic · plotnine · pyplots.ai",
color="Change Direction",
)
+ theme_minimal()
+ theme(
figure_size=(16, 9),
plot_title=element_text(size=24),
axis_title=element_text(size=20),
axis_text=element_text(size=18),
legend_text=element_text(size=16),
legend_title=element_text(size=18),
legend_position="right",
panel_grid_major_x=element_blank(),
panel_grid_minor_x=element_blank(),
)
)
plot.save("plot.png", dpi=300, verbose=False)