草庐IT

跟着NC学作图 | 柱状图与相关性图

小杜的生信筆記 2023-10-15 原文

本期内容为[跟着NC学作图 | 柱状图与相关性图]

本期文章是发表在NC期刊,题目为:Genome-centric analysis of short and long read metagenomes reveals uncharacterized microbiome diversity in Southeast Asians.



本文作者提供了分析的代码和绘制图形的代码。绘图的代码是使用python。对于初学者来说也是比较友好的,自己也是学习Python的态度进行分享。



绘图
Figure 1B
## 数据分析
sdf = df[~ df['genus'].isnull()]

sdf = sdf.groupby('assembly')['genus_first'].value_counts().rename("count").reset_index()
sdf = pd.pivot_table(sdf, index="genus_first", columns="assembly", values="count", fill_value=0)
sdf = sdf.reset_index()

sdf["HybridOnly"] = sdf["Hybrid"] - sdf["Short-read"]
sdf["PRC"]  = sdf["HybridOnly"] / sdf["Hybrid"]

sdf = sdf.sort_values("HybridOnly", ascending=False)

sdf.head()

# Sort by diff
top10 = sdf.sort_values('HybridOnly', ascending=False).head(10)[["genus_first", "Short-read", "HybridOnly"]]

# Next sort by total (should we do that?)
top10['Total'] = top10['HybridOnly'] + top10['Short-read']
top10 = top10.sort_values('Total', ascending=False)

order = list(top10["genus_first"])
top10 = pd.melt(top10, id_vars="genus_first", var_name="assembly", value_name="count")
top10["genus_first"] = pd.Categorical(top10["genus_first"], categories=order)
top10 = top10.sort_values("genus_first")

top10.head(

abu = df[~ df['genus'].isnull()]
abu = abu.groupby(["assembly", "sample", "genus_first", "species"])["abundance"].sum().reset_index()
abu = abu.pivot_table(index=["sample", "species", "genus_first"], columns="assembly", values="abundance", fill_value=0)
abu = abu.reset_index()

abu = abu[(abu["genus_first"].isin(order)) & (abu["Short-read"] == 0)]
abu["genus_first"] = pd.Categorical(abu["genus_first"], categories=order)
abu = abu.sort_values("genus_first")

abu

## 绘图
# Left panel

graph = sc.graph(0, top10)
graph.shs.stacked_barplot(x="genus_first", y="count", hue="assembly", stack_order=["Short-read", "HybridOnly"],
                         palette=cpal[:2], horizontal=True, edgecolor = "black", linewidth=1.5)

graph.ax.invert_xaxis()
graph.ax.set_ylabel("")
graph.ax.set_xlabel("Number of genomes", size=16)
graph.ax.legend(title='')
graph.remove_yticks()

# -------------------------
# Right panel

graph = sc.graph(1, abu)
graph.sns.boxplot(y="genus_first", x="Hybrid", color=cpal[1])

graph.ax.set_ylabel("")
graph.ax.set_xlabel("% abundance", size=16)
graph.apply_yticklabels(size=12)

graph.ax.set_xscale('log')
graph.ax.set_xlim(0, 60)

ticks = [0.1, 1, 2, 5, 10, 25]
graph.ax.set_xticks([], minor=True)
graph.ax.set_xticks(ticks)
graph.ax.set_xticklabels(ticks, size=12)

sc.set_size_inches(6, 4)
sc.tight_layout()
graph.save('../img/f1B.svg')

Figure 1C

## 导入数据
fname = '../tables/kraken_standard_all.parquet.tsv.gz'
standard = pd.read_parquet(fname)

standard = standard[standard['rank'] == 'S']
standard['genus'] = standard['name'].apply(lambda value: value.split()[0])
standard.head()
## 数据分析
bifido_species_anno = set(df[df['genus'] == 'Bifidobacterium']['species'].unique())
bifido_species_standard = set(standard[standard['genus'] == 'Bifidobacterium']['name'].unique())

bifido_common = bifido_species_anno & bifido_species_standard
bifido_common

sdf = df[df['species'].isin(bifido_common)]
sdf = sdf.groupby(["assembly", "sample", "genus", "species"])["abundance"].sum()
sdf = sdf.rename("abundance").reset_index()
sdf = pd.pivot_table(sdf, index=["sample", "species", "genus"], columns="assembly", values="abundance", fill_value=0)
sdf = sdf.reset_index()

standard_bifido = standard[standard['name'].isin(bifido_common)]
standard_bifido = standard_bifido[['sample', 'name', 'abundance']]
standard_bifido.columns = ['sample', 'species', 'Standard']

sdf = sdf.merge(standard_bifido, on=['sample', 'species'], how='left')
sdf.head()
## 绘图
from seahorse import basic_legend

graph = Graph(sdf)
graph.ax.plot([0, 45], [0, 45], linestyle="--", linewidth=1, color="#ca472f") 

graph.sns.scatterplot(x="Standard", y="Short-read", color=cpal[0])
graph.sns.scatterplot(x="Standard", y="Hybrid", color=cpal[1])

basic_legend(graph.ax, {'Hybrid': cpal[1], 'Short-read': cpal[0]})

graph.ax.set_yscale("symlog")
graph.ax.set_xscale("symlog")  

graph.ax.set_ylim((-.2, 45))
graph.ax.set_xlim((-.2, 45))

graph.ax.set_xlabel("Kraken2 abundance", size=16)
graph.ax.set_ylabel("Assembly abundance", size=16)

ticks = [0.1, 1, 10, 20]
graph.ax.set_xticks(ticks)
graph.ax.set_xticklabels(ticks, size=12)
graph.ax.set_yticks(ticks)
graph.ax.set_yticklabels(ticks, size=12)

graph.ax.set_title("Bifidobacterium genomes")
graph.set_size_inches(4, 4)
graph.tight_layout()
graph.save('../img/f1C.svg')

往期文章(总汇)

01-[R语言可视化-精美图形绘制系列]--精美火山图

[02-R语言可视化-精美图形绘制系列--柱状图

[03-R语言可视化-精美图形绘制系列--功能富集分析

[04-R语言可视化-精美图形绘制系列—多组GO富集可视化

05-[R语言可视化-精美图形绘制系列--堆积图]

06-[R语言可视化-精美图形绘制系列--组间相关性分析]

07-[R语言可视化-精美图形绘制系列]--Mental分析

08-[R语言可视化-精美图形绘制系列--复杂热图+两图渐变连线]-【转载】

09-[R语言可视化-精美图形绘制系列--桑基图(Sankey)]

10-[R语言可视化-精美图形绘制系列--柱状图误差线标记]

--

小杜的生信筆記 ,主要发表或收录生物信息学的教程,以及基于R的分析和可视化(包括数据分析,图形绘制等);分享感兴趣的文献和学习资料!

有关跟着NC学作图 | 柱状图与相关性图的更多相关文章

  1. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  2. ruby-on-rails - 在具有 ActiveRecord 条件的相关模型中按字段排序 - 2

    我正在尝试按Rails相关模型中的字段进行排序。我研究的所有解决方案都没有解决如果相关模型被另一个参数过滤?元素模型classItem相关模型:classPriority我正在使用where子句检索项目:@items=Item.where('company_id=?andapproved=?',@company.id,true).all我需要按相关表格中的“位置”列进行排序。问题在于,在优先级模型中,一个项目可能会被多家公司列出。因此,这些职位取决于他们拥有的company_id。当我显示项目时,它是针对一个公司的,按公司内的职位排序。完成此任务的正确方法是什么?感谢您的帮助。PS-我

  3. ruby - 使用指向 ruby​​ 可执行文件的符号链接(symbolic link)时查找相关库 - 2

    假设您有一个可执行文件foo.rb,其库bar.rb的布局如下:/bin/foo.rb/lib/bar.rb在foo.rb的header中放置以下要求以在bar.rb中引入功能:requireFile.dirname(__FILE__)+"../lib/bar.rb"只要对foo.rb的所有调用都是直接的,这就可以正常工作。如果你把$HOME/project和符号链接(symboliclink)foo.rb放入$HOME/usr/bin,然后__FILE__解析为$HOME/usr/bin/foo.rb,因此无法找到bar.rb关于foo.rb的目录名.我意识到像ruby​​gems这

  4. HarmonyOS原子化服务开发相关术语 - 2

    术语中文解释Ability原子化服务帮助用户完成任务的原子化服务,和用户的意图进行关联。Fulfillment服务履行通过图标,卡片,语音等形式呈现用户意图。开发者通过接口的方式,处理用户意图,返回内容。Intent意图用于表达用户想要达成的目标或完成的任务。HUAWEIAssistant智能助手“无微不智”的个人助手,通过不断的学习用户的使用习惯,不断的为用户提供贴心的精准的便捷的个性化服务。AISearch全局搜索用户可快速搜索关键词,与之匹配的原子化服务则会出现在搜索结果中。SmartService智慧服务用户订阅原子化服务,在到达特定触发条件(时间、地点、事件)后,卡片推送至用户智能助

  5. H2数据库配置及相关使用方式一站式介绍(极为详细并整理官方文档) - 2

    目录H2数据库入门以及实际开发时的使用1.H2数据库的初识1.1H2数据库介绍1.2为什么要使用嵌入式数据库?1.3嵌入式数据库对比1.3.1性能对比1.4技术选型思考2.H2数据库实战2.1H2数据库下载搭建以及部署2.1.1H2数据库的下载2.1.2数据库启动2.1.2.1windows系统可以在bin目录下执行h2.bat2.1.2.2同理可以通过cmd直接使用命令进行启动:2.1.2.3启动后控制台页面:2.1.3spring整合H2数据库2.1.3.1引入依赖文件2.1.4数据库通过file模式实际保存数据的位置2.2H2数据库操作2.2.1Mysql兼容模式2.2.2Mysql模式

  6. ruby-on-rails - 旧的 Ruby 错误在我的 Ruby on Rails 应用程序中反复出现,与 Class.create 和 delayed_job 相关 - 2

    这个错误已经有好几个月了,在这里:http://www.ruby-forum.com/topic/1094002其中显示代码更改的两个链接:https://github.com/godfat/ruby/commit/f4e0e8f781b05c767ad2472a43a4ed0727a75708https://github.com/godfat/ruby/commit/c7a6cf975d88828c2ed27d253f41c480f9b66ad6我有Ruby1.9.2和rvm。我会把这些更改粘贴到适当的文件中,但我不知道如何粘贴。这在几天前就奏效了。我不能像这样执行RubyonRai

  7. ruby-on-rails - Searchkick 结果不相关 - 2

    我对相关搜索有疑问。以下请求的结果很奇怪:Candidate.search('martin',fields:[:first_name,:last_name],match::word_start,misspellings:false).map(&:name)["KautzerMartina","FunkMartin","JaskolskiMartin","GutmannMartine","WiegandMartina","SchuellerMartin","DooleyMartin","StiedemannMartine","BartellMartina","GerlachMartine

  8. ruby-on-rails - 我该如何去追踪与 Bundler 相关的 DEPRECATION WARNING - 2

    我是Rails的新手。当我启动我的应用程序时,我不断看到这些弃用警告:DEPRECATIONWARNING:refisdeprecatedandwillberemovedfromRails3.2.(calledfromatD:/dev/AquaticKodiak/config/application.rb:12)DEPRECATIONWARNING:newisdeprecatedandwillberemovedfromRails3.2.(calledfromatD:/dev/AquaticKodiak/config/application.rb:12)好的,第12行是什么?这个:Bun

  9. ruby-on-rails - 使用 Faker gem 生成相关的城市、邮政编码、国家代码值 - 2

    有没有办法得到Fakergem生成“相关的”城市和国家/地区代码值?例如,加利福尼亚州温哥华明尼苏达州明尼阿波利斯我这样做:FactoryGirl.definedofactory:locationdo...city{Faker::Address.city}country_code{['US','CA'].sample}...endend但不能保证city实际位于country_code。我会满足于这样的事情:postal_code{Faker::Address.postcode(['US','CA'].sample)}然后我可以对其进行地理编码以获得其他值。

  10. ruby - 两个Ruby线程相关的问题 - 2

    第一个:如何创建一个不会立即启动的线程。如果我在没有block的情况下使用initialize,则会引发异常。如何将Thread子类化,以便我可以添加一些自定义属性,但保留与Thread基类相同的功能?我也不想为此使用initialize(&block)方法。为了更好地说明这一点:第一个问题:x=Thread.newx.run={#thisshouldhappeninsidethethread}x.start#iwanttomanuallystartthethread对于第二个:x=MyThread.newx.my_attribute=some_valuex.run={#thissho

随机推荐