简体   繁体   English

如何在 plotly(python)中双向 plot plot,两侧均带有正标签?

[英]how to plot bidirectional plot in plotly (python) with positive labels on both side?

I'm trying to create a bi-directional barplot using Plotly in Python. I have used the code given at this link: bi-directional bar chart with annotation in python plotly我正在尝试使用 Python 中的 Plotly 创建一个双向条形图。我使用了此链接中给出的代码: 双向条形图,带注释 python plotly

CODE:代码:

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# define data set
s1 = pd.Series(["negative_regulation_of_axon_extension_involved_in_axon_guidance",4,"regulation_of_neuronal_synaptic_plasticity",5])
s2 = pd.Series(["neuronal_stem_cell_population_maintenance",4,"synapse_assembly",8])
s3 = pd.Series(["neural_crest_cell_migration",5,"neuron_differentiation",11])
s4 = pd.Series(["chromatin_silencing",5,"axon_guidance",15])
s5 = pd.Series(["neuron_differentiation",28,"signal_transduction",113])
df = pd.DataFrame([list(s1),list(s2),list(s3),list(s4),list(s5)], columns = ['label1','value1','label2','value2'])

# create subplots
fig = make_subplots(rows=1, cols=2, specs=[[{}, {}]], shared_xaxes=True,
                    shared_yaxes=True, horizontal_spacing=0)

fig.append_trace(go.Bar(y=df.index, x=df.value1, orientation='h', width=0.4, showlegend=False, marker_color='#4472c4'), 1, 1)
fig.append_trace(go.Bar(y=df.index, x=df.value2, orientation='h', width=0.4, showlegend=False, marker_color='#ed7d31'), 1, 2)
fig.update_yaxes(showticklabels=False) # hide all yticks

annotations = []
for i, row in df.iterrows():
    if row.label1 != '':
        annotations.append({
            'xref': 'x1',
            'yref': 'y1',
            'y': i,
            'x': row.value1,
            'text': row.value1,
            'xanchor': 'right',
            'showarrow': False})
        annotations.append({
            'xref': 'x1',
            'yref': 'y1',
            'y': i-0.3,
            'x': -1,
            'text': row.label1,
            'xanchor': 'right',
            'showarrow': False})            
    if row.label2 != '':
        annotations.append({
            'xref': 'x2',
            'yref': 'y2',
            'y': i,
            'x': row.value2,
            'text': row.value2,
            'xanchor': 'left',
            'showarrow': False})  
        annotations.append({
            'xref': 'x2',
            'yref': 'y2',
            'y': i-0.3,
            'x': 1,
            'text': row.label2,
            'xanchor': 'left',
            'showarrow': False})

fig.update_layout(annotations=annotations)
fig.show()

I'm facing a couple of problems:我面临着几个问题:

  1. In my original data I have data with positive numbers only.在我的原始数据中,我只有正数数据。 But when I'm trying to plot the above data using this code the axis is getting distorted something like this:但是当我尝试使用此代码对上述数据进行 plot 时,轴会像这样扭曲:

在此处输入图像描述

Although if I'm providing the negative numbers for one dataset it's working fine:虽然如果我为一个数据集提供负数它工作正常:

data:数据:

s1 = pd.Series(["negative_regulation_of_axon_extension_involved_in_axon_guidance",-4,"regulation_of_neuronal_synaptic_plasticity",5])
s2 = pd.Series(["neuronal_stem_cell_population_maintenance",-4,"synapse_assembly",8])
s3 = pd.Series(["neural_crest_cell_migration",-5,"neuron_differentiation",11])
s4 = pd.Series(["chromatin_silencing",-5,"axon_guidance",15])
s5 = pd.Series(["neuron_differentiation",-28,"signal_transduction",113])
df = pd.DataFrame([list(s1),list(s2),list(s3),list(s4),list(s5)], columns = ['label1','value1','label2','value2'])

result:结果: 在此处输入图像描述

How to customize the same for the data when I have positive numbers for both axis, so that plot looks like the second image only but has positive numbers on the opposite axis?当我的两个轴都有正数时,如何为数据自定义相同的数据,这样 plot 看起来只像第二张图片,但在相反的轴上有正数?

  1. If we look at the bars in the second image because of the axis, the bar for 4 seems to be bigger than the bar for 8 or 11 on the other side, Will it be possible to change it to relative somehow?如果我们看第二张图片中的条,因为轴,4 的条似乎比另一边的 8 或 11 的条大,是否有可能以某种方式将其更改为相对的?

Thank you.谢谢你。

  • a different approach using Plotly Express使用Plotly Express的不同方法
  • start by restructuring data frame to:首先将数据框重组为:
group团体 label label value价值
1 1个 negative_regulation_of_axon_extension_involved_in_axon_guidance negative_regulation_of_axon_extension_involved_in_axon_guidance 4 4个
1 1个 neuronal_stem_cell_population_maintenance neuronal_stem_cell_population_maintenance 4 4个
1 1个 neural_crest_cell_migration neural_crest_cell_migration 5 5个
1 1个 chromatin_silencing染色质沉默 5 5个
1 1个 neuron_differentiation神经元分化 28 28
2 2个 regulation_of_neuronal_synaptic_plasticity调节_of_neuronal_synaptic_plasticity 5 5个
2 2个 synapse_assembly突触组装 8 8个
2 2个 neuron_differentiation神经元分化 11 11
2 2个 axon_guidance axon_guidance 15 15
2 2个 signal_transduction信号转导 113 113
  • now can do a use group for color and facet_col现在可以为颜色facet_col做一个使用
  • finally format all the axes and layout to achieve your required outcome最后格式化所有轴和布局以获得所需的结果
import plotly.express as px
import pandas as pd

# define data set
s1 = pd.Series(
    [
        "negative_regulation_of_axon_extension_involved_in_axon_guidance",
        4,
        "regulation_of_neuronal_synaptic_plasticity",
        5,
    ]
)
s2 = pd.Series(["neuronal_stem_cell_population_maintenance", 4, "synapse_assembly", 8])
s3 = pd.Series(["neural_crest_cell_migration", 5, "neuron_differentiation", 11])
s4 = pd.Series(["chromatin_silencing", 5, "axon_guidance", 15])
s5 = pd.Series(["neuron_differentiation", 28, "signal_transduction", 113])
df = pd.DataFrame(
    [list(s1), list(s2), list(s3), list(s4), list(s5)],
    columns=["label1", "value1", "label2", "value2"],
)

fig = px.bar(
    pd.wide_to_long(
        df.reset_index(), stubnames=["label", "value"], i="index", j="group"
    )
    .reset_index()
    .drop(columns="index")
    .assign(group=lambda d: d["group"].astype(str)),
    y="label",
    x="value",
    facet_col="group",
    facet_col_spacing=10 ** -9,
    color="group",
    color_discrete_sequence=["#4472c4", "#ed7d31"],
)

fig.update_layout(
    yaxis2={"side": "right", "matches": None, "showticklabels": False},
    yaxis={"showticklabels": False},
    xaxis={"autorange": "reversed"},
    xaxis2={"matches": None},
    showlegend=False,
)
fig.for_each_annotation(lambda a: a.update(text=""))
fig.update_traces(texttemplate="%{y}", textposition="auto")

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM