BaRud
BaRud

Reputation: 3230

pandas plot split long xtickslabels

For a csv like this:

Quartile,KeyArea
Q2,Earth with long name with long name with long name
Q1,Earth with long name with long name
Q1,Fire with long name with long name
,Fire with long name with long name
Q3,Fire with long name with long name
Q1,Space with long name with long name
Q3,Space with long name with long name
Q1,Space with long name with long name
Q4,Space with long name with long name
Q2,Space with long name with long name
,Space with long name with long name
Q2,Air with long name with long name
Q1,Air with long name with long name
Q1,Air with long name with long name
Q1,Air with long name with long name
,Air with long name with long name
Q2,Water with long name with long name
Q2,Water with long name with long name
Q1,Water with long name with long name

I am using code:

import textwrap

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib import cm

matplotlib.use("GTK3Agg")
cmap = cm.get_cmap('tab20')
pd.set_option('display.max_columns', 4)
#  pd.set_option('display.max_rows', None)
dataset = pd.read_csv("mwe.csv")
dsc = dataset.columns

quartiles_df = (dataset.value_counts(subset=[dsc[1], dsc[0]]).reset_index(
    name='count'))
pivoted_df = (quartiles_df.pivot(index='KeyArea',
                                 columns='Quartile',
                                 values='count'))

pivoted_df.plot.bar(stacked=True)
plt.tight_layout()
plt.xlabel("")
plt.show()

The problem is the xtickslabels are very long. How I can wrap texts?

Previous questions like Wrapping long y labels in matplotlib tight layout using setp has a predefined labels, and that can be spilted easily. My problem is, from the csv, pandas get the index and xtickslabel. How I can split labels in this case?

Upvotes: 0

Views: 87

Answers (1)

Cimbali
Cimbali

Reputation: 11405

You can simply rename your plotted dataframe indexes

>>> from textwrap import wrap
>>> pivoted_df.rename(index=lambda l: '\n'.join(wrap(l, 15))).plot.bar(stacked=True, rot=90)
>>> plt.subplots_adjust(bottom=.4)
>>> plt.show()

enter image description here

Upvotes: 1

Related Questions