7

Pandas offers kind='kde' when plotting. In my setting, I would prefer a kde density. The alternative kind='histogram' offers the orientation option: orientation='horizontal', which is strictly necessary for what I am doing. Unfortunately, orientation is not available for kde.

At least this is what I think that happens because I get a

in set_lineprops
    raise TypeError('There is no line property "%s"' % key)
TypeError: There is no line property "orientation"

Is there any straight forward alternative for plotting kde horizontally as easily as it can be done for histogram?

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

plt.ion()

ser = pd.Series(np.random.random(1000))
ax1 = plt.subplot(2,2,1)
ser.plot(ax = ax1, kind = 'hist')
ax2 = plt.subplot(2,2,2)
ser.plot(ax = ax2, kind = 'kde')
ax3 = plt.subplot(2,2,3)
ser.plot(ax = ax3, kind = 'hist', orientation = 'horizontal')

# not working lines below
ax4 = plt.subplot(2,2,4)
ser.plot(ax = ax4, kind = 'kde', orientation = 'horizontal')

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
cattt84
  • 941
  • 1
  • 10
  • 17

1 Answers1

2
import pandas as pd
import numpy as np
import seaborn as sns
from scipy.stats import gaussian_kde

# crate subplots and don't share x and y axis ranges
fig, axes = plt.subplots(2, 2, figsize=(10, 10), sharex=False, sharey=False)

# flatten the axes for easy selection from a 1d array
axes = axes.flat

# create sample data
np.random.seed(2022)
ser = pd.Series(np.random.random(1000)).sort_values()

# plot example plots
ser.plot(ax=axes[0], kind='hist', ec='k')
ser.plot(ax=axes[1], kind='kde')
ser.plot(ax=axes[2], kind='hist', orientation='horizontal', ec='k')

# 1. create kde model
gkde = gaussian_kde(ser)

# 2. create a linspace to match the range over which the kde model is plotted
xmin, xmax = ax2.get_xlim()
x = np.linspace(xmin, xmax, 1000)

# 3. plot the values
axes[3].plot(gkde(x), x)

# Alternatively, use seaborn.kdeplot and skip 1., 2., and 3.
# sns.kdeplot(y=ser, ax=axes[3])

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158