5

我有一个非常大且稀疏的垃圾邮件 Twitter 帐户数据集,它需要我缩放 x 轴以便能够可视化各种变量的分布(直方图、kde 等)和 cdf(tweets_count、关注者/关注者的数量) ETC)。

    > describe(spammers_class1$tweets_count)
  var       n   mean      sd median trimmed mad min    max  range  skew kurtosis   se
1   1 1076817 443.47 3729.05     35   57.29  43   0 669873 669873 53.23  5974.73 3.59

在这个数据集中,值 0 非常重要(实际上 0 应该具有最高的密度)。但是,对于对数刻度,这些值将被忽略。例如,我曾想过将值更改为 0.1,但如果垃圾邮件帐户有 10^-1 个关注者,这将毫无意义。

那么,python 和 matplotlib 中的解决方法是什么?

4

2 回答 2

2

每个x值加 1,然后记录日志:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker

fig, ax = plt.subplots()
x = [0, 10, 100, 1000]
y = [100, 20, 10, 50]
x = np.asarray(x) + 1 
y = np.asarray(y)
ax.plot(x, y)
ax.set_xscale('log')
ax.set_xlim(x.min(), x.max())
ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x-1)))
ax.xaxis.set_major_locator(ticker.FixedLocator(x))
plt.show()

在此处输入图像描述


利用

ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x-1)))
ax.xaxis.set_major_locator(ticker.FixedLocator(x))

根据 的非对数值重新标记刻度线x

(我最初的建议是使用plt.xticks(x, x-1),但这会影响所有轴。为了隔离对某个特定轴的更改,我将所有命令调用更改为ax,而不是调用plt。)


matplotlib删除包含NaN,inf-inf值的点。由于log(0)-inf,对应的点x=0将从对数图中删除。

如果将所有 x 值增加 1,因为log(1) = 0,对应的x=0点将不会绘制在x=log(1)=0对数图上。

剩余的 x 值也将移动 1,但对眼睛来说并不重要,因为对于较大的 值log(x+1)非常接近。log(x)x

于 2013-05-05T09:35:44.180 回答
0
ax1.set_xlim(0, 1e3)

这是 matplotlib 文档中的示例

它以这种方式设置轴的极限值:

ax1.set_xlim(1e1, 1e3)
ax1.set_ylim(1e2, 1e3)
于 2013-05-05T09:25:02.990 回答