【问题标题】:Logarithmic Gridlines for Seaborn FactorplotSeaborn Factorplot 的对数网格线
【发布时间】:2018-08-05 18:06:05
【问题描述】:

我正在尝试在数据帧上使用 seaborn factorplot 绘制对数图,如下所示

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

l1 = [0.476, 0.4427, 0.378, 0.2448, 0.13, 0.004, 0.012, 0.0933, 3.704e-05, 
    1.4762e-06, 4.046e-08, 2.99e-10, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

df = pd.DataFrame(l1, columns=["y"])
df.reset_index(inplace=True)

g = sns.factorplot(x='index',y='y', data=df, aspect=2, size=8)
g.fig.get_axes()[0].set_yscale('log')
plt.grid(True,which="both",ls="--",c='gray')  

plt.show()

我得到下图。

尽管我将 Y 轴刻度更改为对数并使用了两条网格线,但最终数字没有对数刻度刻度。但是,当与另一组值一起使用时,相同的代码给了我下图。在这种情况下,最小值限制为 10^-7

l2 = [0.29, 0.111, 0.0285, 0.0091, 0.00045, 5.49759e-05, 1.88819e-06, 0.0, 0.0, 0.0]
df = pd.DataFrame(l2, columns=["y"])
# same code as above

知道我哪里错了吗?


更新 1

我按照 Diziet 的回答,并按如下方式强制了主要和次要刻度

g.ax.yaxis.set_minor_locator(tkr.LogLocator(base=10, subs='all'))
g.ax.yaxis.set_minor_formatter(tkr.NullFormatter())
g.ax.set_yscale('log')


g.ax.grid(True,which="both",ls="--",c='gray')  

但还是没有解决问题

【问题讨论】:

标签: python pandas matplotlib seaborn


【解决方案1】:

问题在于,为了在自动选择的主要刻度彼此相距十多年的情况下设置刻度的位置,似乎需要设置定位器的 subs 参数以及 @ 987654325@ 手动。在这里,mticker.LogLocator(base=10, subs=np.arange(0.1,1,0.1),numticks=10)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import seaborn as sns

l1 = [0.476, 0.4427, 0.378, 0.2448, 0.13, 0.004, 0.012, 0.0933, 3.704e-05, 
    1.4762e-06, 4.046e-08, 2.99e-10, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] 
df = pd.DataFrame(l1, columns=["y"])
df.reset_index(inplace=True)

g = sns.factorplot(x='index',y='y', data=df, aspect=2, size=8)
g.ax.set_yscale('log')

plt.grid(True,which="both",ls="--",c='gray')  

locmin = mticker.LogLocator(base=10, subs=np.arange(0.1,1,0.1),numticks=10)  
g.ax.yaxis.set_minor_locator(locmin)
g.ax.yaxis.set_minor_formatter(mticker.NullFormatter())

plt.show()

更一般的也看this question

【讨论】:

  • 通过将刻度数更改为 12 而不是 10,我得到了我想要的数字。 locmaj = tkr.LogLocator(base=10.0,numticks=12) g.ax.yaxis.set_major_locator(locmaj) locmin = tkr.LogLocator(base=10.0, subs=np.arange(0.1,1,0.1),numticks=12) g.ax.yaxis.set_minor_locator(locmin) g.ax.yaxis.set_minor_formatter(tkr.NullFormatter())非常感谢
  • 我使用的是 matplotlib 2.2,而另一个问题的答案使用的是早期版本,并且还需要输入 numticks=12。可能在版本之间发生了变化。
【解决方案2】:

我不认为你做错了什么。在我看来,在您的第一个示例中,matplotlib 决定(出于我不知道的原因)不显示任何小刻度,而在第二个示例中确实如此。

解决问题的一种方法是强制显示次要刻度:

g = sns.factorplot(...)

ax = g.axes.flatten()[0]
ax.set_yscale('log')
ax.yaxis.set_minor_locator(matplotlib.ticker.LogLocator(base=10.0, subs='all'))
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

plt.grid(True,which="both",ls="--",c='gray')  

【讨论】:

  • 嗯。抱歉,我很确定解决方案是强制显示小刻度,但我无法重现您的问题,所以除了上面的一般指针之外,我无法弄清楚如何解决它
  • 我已经编辑了这个问题以包含一个最小的数据集以实现可重复性
猜你喜欢
  • 2017-01-02
  • 2018-01-15
  • 2014-10-05
  • 2017-09-29
  • 1970-01-01
  • 1970-01-01
  • 2018-07-09
  • 2015-09-18
  • 1970-01-01
相关资源
最近更新 更多