我需要用 来绘制每日数据sns.lmplot()。
数据具有以下结构:
df = pd.DataFrame(columns=['date', 'origin', 'group', 'value'],
data = [['2001-01-01', "Peter", "A", 1.0],
['2011-01-01', "Peter", "A", 1.1],
['2011-01-02', "Peter", "B", 1.2],
['2012-01-03', "Peter", "A", 1.3],
['2012-01-01', "Peter", "B", 1.4],
['2013-01-02', "Peter", "A", 1.5],
['2013-01-03', "Peter", "B", 1.6],
['2021-01-01', "Peter", "A", 1.7]])
Run Code Online (Sandbox Code Playgroud)
我现在想用每月平均值绘制数据sns.lmplot()(我的原始数据比玩具数据更细粒度)并使用hueforgroup列。为此,我按月汇总:
df['date'] = pd.to_datetime(df['date']).dt.strftime('%Y%M').astype(int)
df = df.groupby(['date', 'origin', 'group']).agg(['mean'])
df.columns = ["_".join(pair) for pair in df.columns] # reset col multi-index
df = df.reset_index() # reset index
Run Code Online (Sandbox Code Playgroud)
然后我绘制数据:
sns.lmplot(data=df, x="date", …Run Code Online (Sandbox Code Playgroud) 我正在使用 Seaborn 在 Python 中创建条形图。我有一个 2(注意力:分散 vs 集中)X 3(解决方案:1,2,3)设计。对于分割,我希望条形颜色为深红色、深绿色、深蓝色。为了集中注意力,我希望条形颜色为红色、绿色、蓝色。
此代码不起作用,因为调色板仅适用于hue参数:
import seaborn as sns
import matplotlib.pyplot as plt
data = sns.load_dataset('attention')
palette = ["darkred", "red", "darkgreen", "green", "darkblue", "blue"]
palette = ["darkred", "darkgreen", "darkblue", "red", "green", "blue"]
sns.set(style='ticks', context='notebook', font_scale=1.2)
fig, ax = plt.subplots(figsize=(7, 5), dpi=96)
my_plot = sns.barplot(x="solutions", y="score", hue="attention",
palette=palette, capsize=.1, ax=ax, data=data)
plt.show()
Run Code Online (Sandbox Code Playgroud)
这段代码几乎可以工作:
import seaborn as sns
import matplotlib.pyplot as plt
data = sns.load_dataset('attention')
sns.set(style='ticks', context='notebook', font_scale=1.5)
fig, ax = plt.subplots(figsize=(7, 5), …Run Code Online (Sandbox Code Playgroud) 我想在我的点上绘制一个更大尺寸的图表,我已经尝试过sizes=100但它不起作用,
这是代码:
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = np.array([[1, 3, 'weekday'], [2, 2.5, 'weekday'],[3, 2.7, 'weekend'], [4, 2.8, 'weekend'], [5, 3, 'weekday'], [6, 3.1, 'weekday'], [7, 3, 'weekday'], [8, 3.1, 'weekday'], [9, 3.1, 'weekday'], [10, 3.1, 'weekend']])
# Creating a data frame with the raw data
dataset = pd.DataFrame(data, columns=['day', 'miles_walked', 'day_category'])
ax = sns.scatterplot(x='day', y='miles_walked', data=dataset, hue='day_category',sizes=100)
# Customize the axes and title
ax.set_title("Miles walked") …Run Code Online (Sandbox Code Playgroud) 我有一个分类数据集,我正在使用 seaborn 绘制条形图。但是,我无法在百分比值的条形顶部添加标签。数据集如下所示:
import pandas as pd
#create DataFrame
df = pd.DataFrame({'Day': ['Mon', 'Tue', 'Wed', 'Thur', 'Fri',
'Mon', 'Tue', 'Wed', 'Thur', 'Fri'],
'Customers': [44, 46, 49, 59, 54,
33, 46, 50, 49, 60],
'Time': ['M', 'M', 'M', 'M', 'M',
'E', 'E', 'E', 'E', 'E']})
#view DataFrame
df
Run Code Online (Sandbox Code Playgroud)
这是绘制分组条形图的代码:
import matplotlib.pyplot as plt
import seaborn as sns
#set seaborn plotting aesthetics
sns.set(style='white')
#create grouped bar chart
sns.barplot(x='Day', y='Customers', hue='Time', data=df)
Run Code Online (Sandbox Code Playgroud)
现在我想在条形顶部添加标签,但以百分比值显示。请帮忙
我正在尝试更改用于在 xarray 中制作构面网格的变量的顺序。例如,我将[a,b,c,d ] 作为列名称。我想将其重新排序为[c,d,a,b]。不幸的是,与seaborn不同,我无法在 xarray 绘图函数中找到 col_order 或 row_order 等参数(
\n\n\nhttps://xarray.pydata.org/en/stable/ generated/xarray.plot.FacetGrid.html
\n
更新: \n为了帮助自己更好地解释我需要什么,我从 xarray 的用户指南中获取了下面的示例:\n在下面的示例中,我需要更改月份的位置。我的意思是,例如,我想将第 7 个月作为第一列,将第 2 个月作为第 5 列,依此类推。
import matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport xarray as xr\nds = xr.tutorial.open_dataset("air_temperature.nc").rename({"air": "Tair"})\n\n# we will add a gradient field with appropriate attributes\nds["dTdx"] = ds.Tair.differentiate("lon") / 110e3 / np.cos(ds.lat * np.pi / 180)\nds["dTdy"] = ds.Tair.differentiate("lat") / 105e3\nds.dTdx.attrs = {"long_name": "$\xe2\x88\x82T/\xe2\x88\x82x$", "units": "\xc2\xb0C/m"}\nds.dTdy.attrs = {"long_name": "$\xe2\x88\x82T/\xe2\x88\x82y$", …Run Code Online (Sandbox Code Playgroud) 我正在使用这个漂亮的箱线图,来自 @Parfait 的回答。
j不得不使用range(i*5,i*5+5). 为什么?red。medianprops=dict(color="red")行不通的。怎么做?免责声明:我不知道我在做什么。
这是使用随机数据的代码:
# import the required library
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import string
import matplotlib.colors as mc
import colorsys
# data
df = pd.DataFrame(np.random.normal(np.random.randint(5,15),np.random.randint(1,5),size=(100, 16)), columns=list(string.ascii_uppercase)[:16])
# Boxplot
fig, ax = plt.subplots(figsize=(9, 10))
medianprops=dict(color="red")
ax = sns.boxplot(data=df, orient="h", showfliers=False, palette = "husl")
ax = sns.stripplot(data=df, orient="h", jitter=True, size=7, …Run Code Online (Sandbox Code Playgroud) 我试图通过以下方式绘制:
g = sns.jointplot(x = etas, y = vs, marginal_kws=dict(bins=100), space = 0)
g.ax_joint.set_xscale('log')
g.ax_joint.set_yscale('log')
g.ax_joint.set_xlim(0.01)
g.ax_joint.set_ylim(0.01)
g.ax_joint.set_xlabel(r'$\eta$')
g.ax_joint.set_ylabel("V")
plt.savefig("simple_scatter_plot_Seanborn.png",figsize=(8,8), dpi=150)
Run Code Online (Sandbox Code Playgroud)
这给我留下了以下图像:

这不是我想要的。为什么最后要填充直方图?那里没有数据点,所以我不明白......
我正在用Python学习乳腺癌分类数据集。我正在尝试为每个特征绘制直方图,如何将这些直方图分为三组?就像下面的截图一样:

这是我使用的代码:
from sklearn.datasets import load_breast_cancer # sample data
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
data = load_breast_cancer()
# Turn the feature data into a dataframe
df = pd.DataFrame(data.data, columns = data.feature_names)
# Add the target columns, and fill it with the target data
df["target"] = data.target
# display(df.head())
mean radius mean texture mean perimeter mean area mean smoothness mean compactness mean concavity mean concave points mean symmetry mean fractal dimension radius error …Run Code Online (Sandbox Code Playgroud) ax.set_axisbelow(True)可以使用或plt.rc('axes', axisbelow=True)(其他堆栈问题)将网格线设置在填充区域的图后面。但使用时alpha<1网格线也会出现在前面。有没有办法仍然隐藏网格线或应用选择性alpha混合?我正在考虑一种基于对象的方法,其中指定对象 a 和 b 之间的 alpha。
答案应该也适用于fill_between。
重现问题的示例:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2022)
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=.3, density=True, bins=40)
fig, ax = plt.subplots(figsize=(9, 6))
ax.hist(x1, **kwargs)
ax.hist(x2, **kwargs)
ax.hist(x3, **kwargs)
ax.set_axisbelow(True)
ax.yaxis.grid(color='gray', linestyle='dashed')
ax.xaxis.grid(color='gray', linestyle='dashed')
Run Code Online (Sandbox Code Playgroud)
我无法更改seaborn中kde线的刻度线。
这是代码行:
sns.kdeplot(ax=ax2,x=dots['Longitude'],y=dots['Latitude'],kde_kws={'linestyle':':'},lw=0.1,levels=10)
Run Code Online (Sandbox Code Playgroud)
是不是少了什么东西?