0
# Core Plot Construction
1
2
The foundation for all plotnine visualizations, providing the main ggplot class for building layered graphics, quick plotting functions for simple visualizations, and save functionality for exporting plots to various formats.
3
4
## Capabilities
5
6
### Main Plot Class
7
8
The ggplot class is the core of plotnine, implementing the Grammar of Graphics approach where plots are built by adding layers with the `+` operator.
9
10
```python { .api }
11
class ggplot:
12
"""
13
Main plotting class that serves as the foundation for all plots.
14
15
Parameters:
16
- data: pandas.DataFrame, the data to be plotted
17
- mapping: aes object, default aesthetic mappings for the plot
18
19
Methods:
20
- save(): Save plot to file
21
- show(): Display plot
22
- draw(): Force drawing of the plot
23
"""
24
def __init__(self, data=None, mapping=None): ...
25
26
def save(self, filename, width=6.4, height=4.8, dpi=100, format=None,
27
units='in', limitsize=True, verbose=True, **kwargs): ...
28
29
def show(self): ...
30
31
def draw(self, return_ggplot=False): ...
32
```
33
34
Usage example:
35
```python
36
import pandas as pd
37
from plotnine import ggplot, aes, geom_point
38
39
data = pd.DataFrame({'x': [1, 2, 3], 'y': [1, 4, 9]})
40
plot = ggplot(data, aes(x='x', y='y')) + geom_point()
41
print(plot) # Display the plot
42
```
43
44
### Quick Plot Function
45
46
The qplot function provides a convenient interface for creating simple plots quickly, similar to R's qplot.
47
48
```python { .api }
49
def qplot(x=None, y=None, data=None, facets="", margins=False, geom="auto",
50
xlim=None, ylim=None, log=None, main=None, xlab=None, ylab=None,
51
asp=None, **kwargs):
52
"""
53
Quick plot function for simple visualizations.
54
55
Parameters:
56
- x, y: str or array-like, variables to plot
57
- data: pandas.DataFrame, data source
58
- facets: str, faceting formula
59
- margins: bool, whether to display marginal facets
60
- geom: str or list, geometric object(s) to use
61
- xlim, ylim: tuple, axis limits
62
- log: str, which axes to log transform ('x', 'y', 'xy')
63
- main: str, plot title
64
- xlab, ylab: str, axis labels
65
- asp: float, aspect ratio
66
- **kwargs: additional aesthetic mappings and parameters
67
68
Returns:
69
ggplot object
70
"""
71
```
72
73
Usage example:
74
```python
75
import pandas as pd
76
from plotnine import qplot
77
78
data = pd.DataFrame({'x': [1, 2, 3], 'y': [1, 4, 9]})
79
plot = qplot(x='x', y='y', data=data, geom='point')
80
```
81
82
### Save Functions
83
84
Functions for saving plots to various file formats and handling multiple plots.
85
86
```python { .api }
87
def ggsave(filename, plot=None, width=6.4, height=4.8, dpi=100, format=None,
88
units='in', limitsize=True, verbose=True, **kwargs):
89
"""
90
Save plot to file (alias for ggplot.save method).
91
92
Parameters:
93
- filename: str, output filename
94
- plot: ggplot object, plot to save (uses last plot if None)
95
- width, height: float, dimensions in specified units
96
- dpi: int, resolution in dots per inch
97
- format: str, file format (inferred from filename if None)
98
- units: str, units for width/height ('in', 'cm', 'mm')
99
- limitsize: bool, whether to limit size to reasonable values
100
- verbose: bool, whether to print save information
101
- **kwargs: additional matplotlib savefig parameters
102
"""
103
104
def save_as_pdf_pages(plots, filename=None, **kwargs):
105
"""
106
Save multiple plots to a single PDF file, one plot per page.
107
108
Parameters:
109
- plots: list of ggplot objects
110
- filename: str, output PDF filename
111
- **kwargs: additional parameters passed to PdfPages and savefig
112
113
Returns:
114
PdfPages object if filename is None, otherwise None
115
"""
116
```
117
118
Usage examples:
119
```python
120
# Save single plot
121
plot.save('my_plot.png', width=8, height=6, dpi=300)
122
123
# Using ggsave
124
ggsave('my_plot.pdf', plot, width=10, height=8)
125
126
# Save multiple plots to PDF
127
plots = [plot1, plot2, plot3]
128
save_as_pdf_pages(plots, 'multiple_plots.pdf')
129
```
130
131
### Plot Display and Interaction
132
133
```python { .api }
134
# Display plot in Jupyter notebook or interactive environment
135
plot # Simply evaluating the plot object displays it
136
137
# Force display
138
print(plot)
139
140
# In Jupyter notebooks, plots display automatically
141
plot # Shows plot inline
142
```
143
144
## Usage Patterns
145
146
### Basic Plot Construction
147
```python
148
# Start with data and aesthetic mappings
149
p = ggplot(data, aes(x='column1', y='column2'))
150
151
# Add geometric objects
152
p = p + geom_point()
153
154
# Add additional layers
155
p = p + geom_smooth(method='lm')
156
157
# Customize appearance
158
p = p + theme_minimal() + labs(title='My Plot')
159
160
# Display or save
161
print(p)
162
p.save('plot.png')
163
```
164
165
### Chained Construction (Recommended)
166
```python
167
plot = (ggplot(data, aes(x='x', y='y')) +
168
geom_point(color='blue', size=3) +
169
geom_smooth(method='lm', color='red') +
170
theme_minimal() +
171
labs(title='Scatter Plot with Trend Line',
172
x='X Variable', y='Y Variable'))
173
```
174
175
### Quick Plotting for Exploration
176
```python
177
# Quick scatter plot
178
qplot('x', 'y', data=df, geom='point')
179
180
# Quick histogram
181
qplot('x', data=df, geom='histogram', bins=30)
182
183
# Quick box plot by group
184
qplot('group', 'value', data=df, geom='boxplot')
185
```