Reordering and facetting for plotnine #709
juanramonua
started this conversation in
Ideas
Replies: 1 comment
-
There is an internal reorder function that you can use inside from string import ascii_lowercase, ascii_uppercase
import numpy as np
import pandas as pd
from plotnine import *
np.random.seed(123)
n = 4
m = 10
df = pd.DataFrame({
"x": list(ascii_lowercase[:m]) * n,
"y": np.random.randint(1, 101, n * m),
"g": np.repeat(list(ascii_uppercase[:n]), m)
})
sep = "::"
(ggplot(df, aes("reorder(x+sep+g, y)", "y", fill="x"))
+ geom_col()
+ labs(x="x")
+ facet_wrap("g", scales="free_x")
+ scale_x_discrete(labels=lambda lst: [l.split(sep)[0] for l in lst])
) You can do some refactoring and use the internal function (not a good idea as the location might change in the future) to get the same result. from string import ascii_lowercase, ascii_uppercase
import numpy as np
import pandas as pd
from plotnine import *
from plotnine.mapping.evaluation import reorder
np.random.seed(123)
n = 4
m = 10
df = pd.DataFrame({
"x": list(ascii_lowercase[:m]) * n,
"y": np.random.randint(1, 101, n * m),
"g": np.repeat(list(ascii_uppercase[:n]), m)
})
sep = "::"
def reorder_within_facet(a, b, facet_var):
_a = a.astype(str) + sep + facet_var.astype(str)
res = reorder(_a, b)
return res
def reordered_labels(labels):
return [l.split(sep)[0] for l in labels]
(ggplot(df, aes("reorder_within_facet(x, y, g)", "y", fill="x"))
+ geom_col()
+ facet_wrap("g", scales="free_x")
+ scale_x_discrete(name="x", labels=reordered_labels)
) The functions |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Reordering labels according to their values by facet is complicated in plotnine. Now, as far as I know there is a trick that consists of creating an auxiliary index, creating the plot with the index and replacing each index with its correct label (e.g.
scale_x_discrete(labels=...)
).In
ggplot2
there is a more intuitive (ej. https://juliasilge.com/blog/reorder-within/) alternative combining thereorder_within(...)
withscale_x_reordered()
functions. My suggestion is to implement these functions in future versions to create this type of graphs in a more intuitive way.Best regards and thanks.
Beta Was this translation helpful? Give feedback.
All reactions