Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使matplotlib图在默认情况下看起来像R?_Python_R_Matplotlib_Plot_Pandas - Fatal编程技术网

Python 使matplotlib图在默认情况下看起来像R?

Python 使matplotlib图在默认情况下看起来像R?,python,r,matplotlib,plot,pandas,Python,R,Matplotlib,Plot,Pandas,有没有办法使matplotlib在打印默认值方面的行为与R相同,或几乎与R相似?例如,R对其轴的处理与matplotlib非常不同。下面的柱状图 具有带有向外刻度的“浮动轴”,因此没有内部刻度(与matplotlib不同,matplotlib),且轴不会“靠近”原点交叉。此外,直方图可能会“溢出”到没有标记记号的值,例如,x轴在3处结束,但直方图会稍微超出它。如何为matplotlib中的所有直方图自动实现这一点 相关问题:散点图和直线图在R中有不同的默认轴设置,例如: 再次没有内部滴答声,

有没有办法使
matplotlib
在打印默认值方面的行为与R相同,或几乎与R相似?例如,R对其轴的处理与
matplotlib
非常不同。下面的柱状图

具有带有向外刻度的“浮动轴”,因此没有内部刻度(与matplotlib不同,matplotlib),且轴不会“靠近”原点交叉。此外,直方图可能会“溢出”到没有标记记号的值,例如,x轴在3处结束,但直方图会稍微超出它。如何为
matplotlib
中的所有直方图自动实现这一点

相关问题:散点图和直线图在R中有不同的默认轴设置,例如:

再次没有内部滴答声,滴答声面向外部。此外,记号在原点(y轴和x轴在轴的左下角交叉处)之后稍开始,记号在轴结束之前稍结束。这样,最低x轴刻度和最低y轴刻度的标签就不能真正交叉,因为它们之间有一个空间,这给了绘图一个非常优雅干净的外观。请注意,轴标签和记号本身之间也有相当多的空间

此外,默认情况下,未标记的x轴或y轴上没有记号,这意味着左侧与右侧标记的y轴平行的y轴没有记号,x轴也没有记号,这同样可以消除绘图中的杂波

有没有办法让matplotlib看起来像这样?一般来说,默认情况下看起来和默认R图一样多?我非常喜欢matplotlib,但我认为R默认值/开箱即用打印行为确实正确,其默认设置很少导致标记标签重叠、混乱或数据挤压,因此我希望默认值尽可能类似于此。

我想检查一下“在R中提供一个引人注目的Python等价物ggplot”。示例

编辑:也可以签出,它尝试重现ggplot2的视觉样式和语法。

1年后编辑: 使用
seaborn
,以下示例变为:

import numpy as np
import matplotlib.pyplot as plt
import seaborn
seaborn.set(style='ticks')
# Data to be represented
X = np.random.randn(256)

# Actual plotting
fig = plt.figure(figsize=(8,6), dpi=72, facecolor="white")
axes = plt.subplot(111)
heights, positions, patches = axes.hist(X, color='white')
seaborn.despine(ax=axes, offset=10, trim=True)
fig.tight_layout()
plt.show()
很简单

原职: 这篇博文是我迄今为止看到的最好的一篇。

它不像大多数“入门”类型的示例那样关注标准的R绘图,而是尝试模仿ggplot2的风格,ggplot2似乎被普遍认为是时尚且设计精良的

要像在条形图中看到的那样获得轴脊椎,请尝试遵循此处的前几个示例之一:

最后,要获得指向外部的轴刻度线,可以编辑
matplotlibrc
文件,使其显示
xtick.direction:out
ytick.direction:out

将这些概念结合在一起,我们得到如下结果:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# Data to be represented
X = np.random.randn(256)

# Actual plotting
fig = plt.figure(figsize=(8,6), dpi=72, facecolor="white")
axes = plt.subplot(111)
heights, positions, patches = axes.hist(X, color='white')

axes.spines['right'].set_color('none')
axes.spines['top'].set_color('none')
axes.xaxis.set_ticks_position('bottom')

# was: axes.spines['bottom'].set_position(('data',1.1*X.min()))
axes.spines['bottom'].set_position(('axes', -0.05))
axes.yaxis.set_ticks_position('left')
axes.spines['left'].set_position(('axes', -0.05))

axes.set_xlim([np.floor(positions.min()), np.ceil(positions.max())])
axes.set_ylim([0,70])
axes.xaxis.grid(False)
axes.yaxis.grid(False)
fig.tight_layout()
plt.show()
可以通过多种方式指定脊椎的位置。如果在IPython中运行上述代码,则可以执行
axes.spines['bottom']。设置位置?
以查看所有选项

所以是的。这并不简单,但你可以接近它。

# # # # # #

2013年10月14日编辑: 作为参考,ggplot现在已经为python实现(基于matplotlib构建)

有关更多信息和示例,请参见此部分或直接转到项目的第页

# # # # # #

据我所知,matplotlib中没有内置的解决方案可以直接为您的图形提供与R相似的外观

有些软件包(如)使用Matplotlib的rc参数添加了对样式表的支持,并可以帮助您获得ggplot外观(请参阅以获取示例)

但是,由于matplotlib中的所有内容都可以调整,因此您可以更轻松地直接开发自己的函数,以完全实现所需的功能。例如,下面是一个片段,可用于轻松自定义任何matplotlib绘图的轴

def customaxis(ax, c_left='k', c_bottom='k', c_right='none', c_top='none',
               lw=3, size=20, pad=8):

    for c_spine, spine in zip([c_left, c_bottom, c_right, c_top],
                              ['left', 'bottom', 'right', 'top']):
        if c_spine != 'none':
            ax.spines[spine].set_color(c_spine)
            ax.spines[spine].set_linewidth(lw)
        else:
            ax.spines[spine].set_color('none')
    if (c_bottom == 'none') & (c_top == 'none'): # no bottom and no top
        ax.xaxis.set_ticks_position('none')
    elif (c_bottom != 'none') & (c_top != 'none'): # bottom and top
        ax.tick_params(axis='x', direction='out', width=lw, length=7,
                      color=c_bottom, labelsize=size, pad=pad)
    elif (c_bottom != 'none') & (c_top == 'none'): # bottom but not top
        ax.xaxis.set_ticks_position('bottom')
        ax.tick_params(axis='x', direction='out', width=lw, length=7,
                       color=c_bottom, labelsize=size, pad=pad)
    elif (c_bottom == 'none') & (c_top != 'none'): # no bottom but top
        ax.xaxis.set_ticks_position('top')
        ax.tick_params(axis='x', direction='out', width=lw, length=7,
                       color=c_top, labelsize=size, pad=pad)
    if (c_left == 'none') & (c_right == 'none'): # no left and no right
        ax.yaxis.set_ticks_position('none')
    elif (c_left != 'none') & (c_right != 'none'): # left and right
        ax.tick_params(axis='y', direction='out', width=lw, length=7,
                       color=c_left, labelsize=size, pad=pad)
    elif (c_left != 'none') & (c_right == 'none'): # left but not right
        ax.yaxis.set_ticks_position('left')
        ax.tick_params(axis='y', direction='out', width=lw, length=7,
                       color=c_left, labelsize=size, pad=pad)
    elif (c_left == 'none') & (c_right != 'none'): # no left but right
        ax.yaxis.set_ticks_position('right')
        ax.tick_params(axis='y', direction='out', width=lw, length=7,
                       color=c_right, labelsize=size, pad=pad)
编辑:对于非接触脊椎,请参见下面的函数,该函数会导致脊椎位移10磅(取自matplotlib网站)

例如,下面的代码和两个图显示matplotib的默认输出(左侧)和调用函数时的输出(右侧):


当然,要想弄清楚matplotlib中需要调整哪些参数才能使绘图与R绘图完全相同,还需要时间,但我不确定现在是否还有其他选项。

以下是一篇您可能感兴趣的博文:

熊猫GSoC2012的绘图

决定尝试实现ggplot2类型的打印接口…尚不确定要实现多少ggplot2功能

作者把熊猫分成两半,为熊猫建立了很多类似ggplot2风格的语法

plot = rplot.RPlot(tips_data, x='total_bill', y='tip')
plot.add(rplot.TrellisGrid(['sex', 'smoker']))
plot.add(rplot.GeomHistogram())
plot.render(plt.gcf())

熊猫叉在这里:

制作受R影响的图形的代码似乎包含在一个名为
rplot.py
的文件中,该文件可以在repo的分支中找到

class GeomScatter(Layer):
    """
    An efficient scatter plot, use this instead of GeomPoint for speed.
    """

class GeomHistogram(Layer):
    """
    An efficient histogram, use this instead of GeomBar for speed.
    """
链接到分支机构:

我认为这真的很酷,但我不知道这个项目是否正在维护。上次提交是在不久前。

解释了为什么不能简单地编辑Matplotlib默认值以生成R样式的直方图。对于散点图, 并显示一些可以更改的默认值,以提供更具R风格的外观。基于其他一些答案,假设您使用
facecolor='none'
轴上调用了
hist()
实例,下面的函数可以很好地模拟R的直方图样式

def Rify(axes):
    '''
    Produce R-style Axes properties
    '''
    xticks = axes.get_xticks() 
    yticks = axes.get_yticks()

    #remove right and upper spines
    axes.spines['right'].set_color('none') 
    axes.spines['top'].set_color('none')

    #make the background transparent
    axes.set_axis_bgcolor('none')

    #allow space between bottom and left spines and Axes
    axes.spines['bottom'].set_position(('axes', -0.05))
    axes.spines['left'].set_position(('axes', -0.05))

    #allow plot to extend beyond spines
    axes.spines['bottom'].set_bounds(xticks[0], xticks[-2])
    axes.spines['left'].set_bounds(yticks[0], yticks[-2])

    #set tick parameters to be more R-like
    axes.tick_params(direction='out', top=False, right=False, length=10, pad=12, width=1, labelsize='medium')

    #set x and y ticks to include all but the last tick
    axes.set_xticks(xticks[:-1])
    axes.set_yticks(yticks[:-1])

    return axes
matplotlib>=1.4支持(并且内置ggplot样式):


将matplotlib.pyplot导入为plt
plt.style.use('ggplot')

在这里做一些绘图,并享受它

Seaborn可视化库可以做到这一点
class GeomScatter(Layer):
    """
    An efficient scatter plot, use this instead of GeomPoint for speed.
    """

class GeomHistogram(Layer):
    """
    An efficient histogram, use this instead of GeomBar for speed.
    """
def Rify(axes):
    '''
    Produce R-style Axes properties
    '''
    xticks = axes.get_xticks() 
    yticks = axes.get_yticks()

    #remove right and upper spines
    axes.spines['right'].set_color('none') 
    axes.spines['top'].set_color('none')

    #make the background transparent
    axes.set_axis_bgcolor('none')

    #allow space between bottom and left spines and Axes
    axes.spines['bottom'].set_position(('axes', -0.05))
    axes.spines['left'].set_position(('axes', -0.05))

    #allow plot to extend beyond spines
    axes.spines['bottom'].set_bounds(xticks[0], xticks[-2])
    axes.spines['left'].set_bounds(yticks[0], yticks[-2])

    #set tick parameters to be more R-like
    axes.tick_params(direction='out', top=False, right=False, length=10, pad=12, width=1, labelsize='medium')

    #set x and y ticks to include all but the last tick
    axes.set_xticks(xticks[:-1])
    axes.set_yticks(yticks[:-1])

    return axes
In [1]: import matplotlib as mpl

In [2]: import matplotlib.pyplot as plt

In [3]: import numpy as np

In [4]: mpl.style.available
Out[4]: [u'dark_background', u'grayscale', u'ggplot']

In [5]: mpl.style.use('ggplot')

In [6]: plt.hist(np.random.randn(100000))
Out[6]: 
...
sns.despine(offset=10, trim=True)
sns.set_style("ticks")