How to rotate the xticks with seaborn.objects
Asked Answered
E

2

5

By chance, is there a way to rotate the xticks in the graphic below (just to make it a bit more readable)? The usual sns.xticks() doesn't work in the new seaborn.objects development (which is amazing!)

tcap.\
    assign(date_time2 = tcap['date_time'].dt.date).\
    groupby(['date_time2', 'person']).\
    agg(counts = ('person', 'count')).\
    reset_index().\
    pipe(so.Plot, x = "date_time2", y = "counts", color = "person").\
            add(so.Line(marker="o", edgecolor="w")).\
            label(x = "Date", y = "# of messages",
                  color = str.capitalize,
                  title = "Plot 2: Volume of messages by person, by day").\
            scale(color=so.Nominal(order=["lorne_a_20014", "kayla_princess94"])).\
            show()

enter image description here

In addition, my x-axis is categorical and this warning: Using categorical units to plot a list of strings that are all parsable as floats or dates. If these strings should be plotted as numbers, cast to the appropriate data type before plotting. appears. I tried using:

import warnings
warnings.filterwarnings("ignore",category=UserWarning)
Exceptional answered 7/12, 2022 at 11:17 Comment(1)
For the same question not with seaborn.objects, see Rotate label text in seabornLaritalariviere
A
5

This can be done by creating an Axis object, rotating the axes there, and then using the so.Plot().on() method to apply the rotated-axis labels. Note this will not work if you also plan to add facets (I found your question while coming to ask about how to combine this with facets).

import seaborn.objects as so
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'a':[1,2,3],
                   'b':[4,5,6]})

fig, ax = plt.subplots()
ax.xaxis.set_tick_params(rotation=90)

(so.Plot(df, x = 'a', y = 'b')
 .add(so.Line())
 .on(ax))

Line graph with rotated x-axis labels

Akins answered 7/1, 2023 at 8:50 Comment(0)
T
1

The answer involving plotting it on matplotlib axes you create is probably the right way to go, but doing so changes the layout engine that seaborn uses. Fortunately, you can actually get the underlying the Figure that seaborn plots on and manipulate that directly, but this does rely on interacting with seaborn's internals, and so likely will break in future versions.

You can get axis to the underlying figure and change the tick label rotation like so:

# This gives you the Plotter object used for rendering the plot
p = so.Plot(...).add(so.Line()).plot()
# Then you can get the internal Figure object with `._figure`:
p._figure.axes[0].xaxis.set_tick_params(rotation=90)

You can then render with p.show() or display(p) or p.save(...) as normal.

Tridactyl answered 13/11, 2023 at 22:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.