标签: seaborn

在 matplotlib/seaborn 中设置子图的边距

我正在使用以下命令在 matplotlib/seaborn 中绘制子图:

plt.figure()
s1 = plt.subplot(2, 1, 1)
# plot 1 
# call seaborn here
s2 = plt.subplot(2, 1, 2)
# plot 2
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

我遇到了标记被轴隐藏的常见问题(当绘图靠近图形边缘时添加边距)。当我尝试调整边距时,它不起作用:

s1 = plt.subplot(2, 1, 1)
s1.margins(0.05)
Run Code Online (Sandbox Code Playgroud)

它没有给出错误,但也没有设置边距。

这是一个完整的例子:

gammas = sns.load_dataset("gammas")
s = plt.subplot(1, 1, 1)
# this does not change the x margins
s.get_axes().margins(x=0.05, y=0.01)
ax = sns.tsplot(time="timepoint", value="BOLD signal",
                unit="subject", condition="ROI",
                err_style="ci_bars",
                interpolate=False,
                data=gammas)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在上面,我试图使 x 边距更大,但 的x参数margins()似乎没有效果。如何才能做到这一点?

python matplotlib seaborn

1
推荐指数
1
解决办法
1万
查看次数

Seaborn 设置 figsize=(x,y) 错误和关于紧缩布局的警告“tight_layout 不能使轴高度小到足以容纳所有轴装饰”

我在 Seaborn 中有一个 10-plot FacetGrid 图表,其中的图略有重叠。我想改变整体图的大小。当我在下面的代码中使用 g.fig.subplots(figsize=(12,12)) 时,我收到一条错误消息TypeError: subplots() got an unexpected keyword argument 'size'

另外,我收到警告 UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations self.fig.tight_layout()

我在我的代码中没有看到引用了 tiny_layout() 的任何地方。它嵌入在模块中:C:\Anaconda3\lib\site-packages\seaborn\axisgrid.py:848. 我不想在站点包模块中乱搞。如何调整参数以免收到此警告。

我想解决这个问题,而不仅仅是抑制这个警告。我对 Seaborn 和 Matplotlib 的内部结构知之甚少,无法修复此错误并消除警告。

我尝试添加g.fig.subplots(figsize=(12,12))以更改图形大小。显然 FacetGrid 图不包含在图形中,或者我错误地引用了图形边界框对象。

"""
FacetGrid Plot Showing Overlapping Distributions (Densities) Offset by ('ridge plot')
====================================
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as …
Run Code Online (Sandbox Code Playgroud)

matplotlib python-3.x seaborn

1
推荐指数
1
解决办法
1916
查看次数

将字符串 xticks 拆分为多行 (matplotlib)

我有一个很长的字符串作为 xticks 的 matplotlib boxplot。有没有办法自动将它们分成多行以使情节更干净?我正在使用 seaborn 函数barplot来创建图形。

这是情节:在此处输入图片说明

我用来创建它的代码:

plt.figure(figsize=(15,13))
sns.barplot(x="Component",y="TTTR",color = "C0",data=new,dodge=False,edgecolor="black",zorder=3)
plt.xticks(rotation=90)
plt.grid(axis='y',zorder=0)
plt.title("10 most impactful components",size=30,y=1.04,**pfont)
plt.ylabel("Impact (Sum TTR in h)")
plt.xlabel('Component')
plt.tight_layout()
Run Code Online (Sandbox Code Playgroud)

python matplotlib seaborn

1
推荐指数
1
解决办法
1929
查看次数

PairGrid python seaborn 中的堆叠条形图

我希望重现该教程中的 PairGrid 图,但在本地我的条形图不像教程中那样堆叠,我不知道如何使它们如此。

import seaborn as sns
import matplotlib.pyplot as plt  # for graphics
import os
os.sys.version
# '3.6.4 (default, Sep 20 2018, 19:07:50) \n[GCC 5.4.0 20160609]'

sns.__version__    
# '0.9.0'

mpg = sns.load_dataset('mpg')

g = sns.PairGrid(data=mpg[["mpg", "horsepower", "weight", "origin"]], hue="origin")
g.map_upper(sns.regplot)
g.map_lower(sns.residplot)

# below for the histogram
g.map_diag(plt.hist)

# also I tried
# g.map_diag(lambda x, label, color: plt.hist(x, label=label, color=color, histtype='barstacked', alpha=.4))
# g.map_diag(plt.hist, histtype='barstacked')
# but same result

g.savefig('./Plots/mpg.svg')

Run Code Online (Sandbox Code Playgroud)

我的情节

教程的情节

我是否必须遵循此帖子答案的第二个答案,这表明处理 seaborn 非常棘手,还是应该按照此处的建议返回 plt …

python matplotlib seaborn

1
推荐指数
1
解决办法
674
查看次数

如何在图中表示非常大和非常小的值

我需要在直方图中绘制 3 个值。与其他值相比,其中一个值非常大。当我尝试绘制它们时,由于较大的另外两个值没有显示在图中。除了 Python 中的直方图之外,还有什么方法可以用图表来说明它们吗?是否有任何缩放技巧来解决这个问题? 

下面给出的代码是我试过的。我使用 python 库 numpy 和 matplotlib 来绘制图形。

import numpy as np
import matplotlib.pyplot as plt

height = [0.422602, 0.000011, 0.000453]
bars = ('2X2', '4X4', '8X8')
y_pos = np.arange(len(bars))

plt.bar(y_pos, height, color = (0.572549,0.2862,0.0,1))
plt.xlabel('Matrix Dimensions')
plt.ylabel('Fidelity for Matrices with Sparsity 1')
plt.xticks(y_pos, bars)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

输出是上面包含的图片。此图未描绘其他两列的值。我怎么解决这个问题?

python matplotlib bar-chart pandas seaborn

1
推荐指数
1
解决办法
2670
查看次数

编辑 Seaborn 散点图和计数图的图例标题

我在泰坦尼克号数据集上使用 seaborn 散点图和计数图。
这是我绘制散点图的代码。我还尝试编辑图例标签。

ax = seaborn.countplot(x='class', hue='who', data=titanic)
legend_labels, _= ax.get_legend_handles_labels()
pyplot.show();
Run Code Online (Sandbox Code Playgroud)

输出

为了编辑图例标签,我这样做了。在这种情况下,不再有图例标题。如何将此标题从 'who' 重命名为 'who1' ?

ax = seaborn.countplot(x='class', hue='who', data=titanic)
legend_labels, _= ax.get_legend_handles_labels()
ax.legend(legend_labels, ['man1','woman1','child1'], bbox_to_anchor=(1,1))
pyplot.show();
Run Code Online (Sandbox Code Playgroud)

输出2

我使用相同的方法编辑散点图上的图例标签,结果在这里有所不同。它使用 'dead' 作为图例标题,并使用 'survied' 作为第一个图例标签。

ax = seaborn.scatterplot(x='age', y='fare', data=titanic, hue = 'survived')
legend_labels, _= ax.get_legend_handles_labels()
ax.legend(legend_labels, ['dead', 'survived'],bbox_to_anchor=(1.26,1))
pyplot.show();
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

(1) 是否有删除和添加图例标题的参数?

(2) 我在两个不同的图上使用了相同的代码,图例的结果是不同的。为什么?

谢谢

python data-visualization matplotlib legend seaborn

1
推荐指数
1
解决办法
4039
查看次数

如何使用 python 字典中的 seaborn 绘制一个简单的图?

我有一本这样的字典:

my_dict = {'Southampton': '33.7%', 'Cherbourg': '55.36%', 'Queenstown': '38.96%'}
Run Code Online (Sandbox Code Playgroud)

我怎样才能有一个带有 3 个条形图的简单图,显示字典中每个键的值?

我试过了:

sns.barplot(x=my_dict.keys(), y = int(my_dict.values()))
Run Code Online (Sandbox Code Playgroud)

但我得到:

类型错误:int() 参数必须是字符串、类似字节的对象或数字,而不是“dict_values”

python matplotlib seaborn

1
推荐指数
1
解决办法
4370
查看次数

显示与行颜色对应的 seaborn clustermap 的图例

''' 为简单起见,让我们使用 iris 数据集。我想添加一个将每个物种与其颜色代码匹配的图例(在本例中为蓝色、绿色、红色)。顺便说一句,我在以下链接中发现了类似的问题,但更复杂一些。 如何在 Seaborn 中的热图轴上表达类

Seaborn clustermap row color with legend 中提出的解决方案会起作用,但是对于 df[['tissue type','label']] 在定义 legend_TN 时,我不确定如何类似地定义标签,例如 iris['species' ,'xxxx'] 预先感谢您帮助我。'''

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

iris = sns.load_dataset('iris')
species = iris.pop('species')


lut = dict(zip(species.unique(), "rbg"))
row_colors = species.map(lut)
g = sns.clustermap(iris, row_colors=row_colors)
plt.show()
Run Code Online (Sandbox Code Playgroud)

colors legend heatmap seaborn

1
推荐指数
1
解决办法
1458
查看次数

根据seaborn热图的条件更改颜色

我用 seaborn 生成了一个热图,代码如下:

sns.heatmap(df.sort_index(axis=1), cmap="YlOrRd_r", center=0.8, square=True, annot=annot_df.sort_index(axis=1), annot_kws={"size":22, "va": "center_baseline", "color":"white"}, fmt="", xticklabels=True, yticklabels=True, linewidth=1, linecolor="grey", vmax=1, vmin=0.5)
Run Code Online (Sandbox Code Playgroud)

现在我想用不同的颜色,例如蓝色,所有值 > 0.9 的单元格,而其他单元格应该保留红色到黄色的调色板。有没有简单的方法来实现这一点?先感谢您!

python heatmap seaborn

1
推荐指数
1
解决办法
1135
查看次数

在 seaborn 散点图中对分类 x 轴进行排序

我正在尝试使用 seaborn 散点图在数据框中绘制前 30% 的值,如下所示。

在此处输入图片说明

同一图的可重现代码:

import seaborn as sns

df = sns.load_dataset('iris')

#function to return top 30 percent values in a dataframe.
def extract_top(df):
    n = int(0.3*len(df))
    top = df.sort_values('sepal_length', ascending = False).head(n)

    return top

#storing the top values
top = extract_top(df)

#plotting
sns.scatterplot(data = top,
                x='species', y='sepal_length', 
                color = 'black',
                s = 100,
                marker = 'x',)
Run Code Online (Sandbox Code Playgroud)

在这里,我想对 x 轴进行排序order = ['virginica','setosa','versicolor']。当我尝试order用作 中的参数之一时sns.scatterplot(),它返回了一个错误AttributeError: 'PathCollection' object has no property 'order'。正确的做法是什么?

请注意:在数据框中,setosa …

python matplotlib scatter-plot pandas seaborn

1
推荐指数
1
解决办法
1688
查看次数