In Lets-Plot you can apply a formatting to:
geom_text()
.Using format string you can format values of numeric and date-time types.
In addition, you can use a string template.
In string template the value's format string is surrounded by curly braces: "... {.2f} ..."
.
An empty placeholder {}
is also allowed. In this case a default string representation will be shown. This is also applicable to categorical values.
See Formatting documentation page to find information about supported format strings and string templates.
import numpy as np
import pandas as pd
from lets_plot import *
LetsPlot.setup_html()
economics_url = 'https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/economics.csv'
economics = pd.read_csv(economics_url, parse_dates=['date'])
start_date = economics['date'].min()
economics.head(3)
Unnamed: 0 | date | pce | pop | psavert | uempmed | unemploy | |
---|---|---|---|---|---|---|---|
0 | 1 | 1967-07-01 | 506.7 | 198712.0 | 12.6 | 4.5 | 2944 |
1 | 2 | 1967-08-01 | 509.8 | 198911.0 | 12.6 | 4.7 | 2945 |
2 | 3 | 1967-09-01 | 515.6 | 199113.0 | 11.9 | 4.6 | 2958 |
p = (ggplot(economics, aes('date', 'uempmed')) +
geom_line() +
ylab("unemployment rate") +
ggsize(900, 400)
)
p + scale_x_datetime()
Use the format
parameter in scale_xxx()
.
Note that the text in tooltips is now also formatted.
(p +
scale_x_datetime(format="%b %Y") +
scale_y_continuous(format="{} %"))
breaks = pd.date_range(
pd.to_datetime("2001-01-01"),
pd.to_datetime("2016-01-01"),
freq='5YS'
).to_pydatetime()
(p +
scale_x_datetime(format="%b %Y", breaks=breaks) +
scale_y_continuous(format="{} %")
)
(ggplot(economics, aes('date', 'uempmed')) +
geom_line(tooltips=layer_tooltips()
.line("Unemployment rate:|^y")
.anchor("top_center")
.min_width(170)) +
scale_x_datetime(format="%b %Y") +
scale_y_continuous(format="{} %") +
ylab("unemployment rate") +
ggsize(900, 400))
(ggplot(economics, aes('date', 'uempmed')) +
ylab("unemployment rate") +
scale_x_datetime() +
scale_y_continuous() +
geom_line(tooltips=layer_tooltips()
.line('@uempmed % in @date')
.format('date', '%B %Y')
.anchor("top_left")
.min_width(170)) +
ggsize(900, 400)
)
The geom_text
label is formatted using the label_format
parameter.
unemployment_mean = economics["uempmed"].mean()
(ggplot(economics, aes('date', 'uempmed')) +
geom_line(tooltips=layer_tooltips()
.line("Unemployment rate:|^y")
.anchor("top_center")
.min_width(170)) +
geom_hline(yintercept=unemployment_mean, color="red", linetype="dashed") +
geom_text(label=unemployment_mean,
label_format="{.2f} %",
x=start_date, y=unemployment_mean+.5,
color="red") +
scale_x_datetime(format="%b %Y") +
scale_y_continuous(format="{} %") +
ylab("unemployment rate") +
ggtitle("The US Unemployment Rates 2000-2016.") +
ggsize(900, 400))