在Pandas中使散点图的标签垂直和水平

时间:2014-11-17 14:38:49

标签: python pandas

我使用Pandas绘制散点图矩阵:from pandas.tools.plotting import scatter_matrix。问题是DataFrame中列的名称太长,我需要它们在x轴上是垂直的,在y轴上是水平的,所以它们可以适合。我根本无法弄清楚如何在熊猫中做到这一点。我知道如何在matplotlib中完成,而不是在Pandas中。

我的代码:

pylab.clf()
df = pd.DataFrame(X, columns=the_labels)
axs = scatter_matrix(df, alpha=0.2, diagonal='kde')

编辑: 我需要使用pylab.clf(),因为我正在绘制大量数据,因此每次调用pylab.figure()都会占用大量内存。

2 个答案:

答案 0 :(得分:10)

这个答案的主要帮助:https://stackoverflow.com/a/18994338/2632856

a = [[1,2], [2,3], [3,4], [4, 5], [1, 6], [2,7], [1,8]]
df = pd.DataFrame(a,columns=['askdabndksbdkl','aooweoiowiaaiwi'])
axs = pd.scatter_matrix( df, alpha=0.2, diagonal='kde')
n = len(df.columns)
for x in range(n):
    for y in range(n):
        # to get the axis of subplots
        ax = axs[x, y]
        # to make x axis name vertical  
        ax.xaxis.label.set_rotation(90)
        # to make y axis name horizontal 
        ax.yaxis.label.set_rotation(0)
        # to make sure y axis names are outside the plot area
        ax.yaxis.labelpad = 50

enter image description here

答案 1 :(得分:5)

scatter_matrix返回matplotlib子图的二维数组。这意味着您应该能够遍历两个数组并使用matplotlib函数来旋转轴。基于用于实现scatter_matrix的源和私有帮助函数_label_axis,看起来您应该能够对所有绘图执行旋转:

from matplotlib.artist import setp

x_rotation = 90
y_rotation = 90

for row in axs:
    for subplot in row:
        setp(subplot.get_xticklabels(), rotation=x_rotation)
        setp(subplot.get_yticklabels(), rotation=y_rotation)

我没有一个好的方法来测试这个,所以它可能需要一些游戏。