【问题标题】:How to make a plotly bar graph with the correct value count with python?如何使用python制作具有正确值计数的绘图条形图?
【发布时间】:2021-12-14 20:23:04
【问题描述】:

数据看起来像这样

A label
string negative
string negative
string negative
string positive
string positive
string negative
string positive

我想制作一个简单的条形图,显示两个条形 - 正数和负数,彼此相邻,蓝色和红色。

如果我这样做

fig = px.bar(df, x=df["label"])

然后我明白了(顺便说一句,你知道为什么颜色会突然变暗吗?):

当我将鼠标悬停时,它会显示“count = 1”,我希望它显示实际计数……并且我想让负数条变为红色。我该怎么做?

【问题讨论】:

标签: python pandas plotly bar-chart


【解决方案1】:

plotly 具有直方图图表类型。 https://plotly.com/python/histograms/

import io
import pandas as pd
import plotly.express as px

df = pd.read_csv(io.StringIO("""A,label
string,negative
string,negative
string,negative
string,positive
string,positive
string,negative
string,positive"""))

px.histogram(df, x="label", color="label", color_discrete_sequence=["red","blue"])

【讨论】:

    【解决方案2】:

    执行groupby 并与count 聚合以获得一个新的DataFrame,其中包含label 下的两个类的计数:

    fig = px.bar(df.groupby([‘a’]).count(),x=‘label’,color =‘label’, color_discrete_sequence=[‘blue’,’red’])
    

    【讨论】:

      猜你喜欢
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      相关资源
      最近更新 更多