在pandas datafram中绘制水平条

2024-10-01 09:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个sales pandas数据框,其中每一行代表一个公司名称,有四列显示最近五年的当前、最小、最大和平均销售额。在

我想知道是否有一种方法来绘制数据帧内的最小值、最大值、平均值、当前水平线。在

举个具体的例子: https://libguides.lib.umanitoba.ca/bloomberg/fixedincome

如果你看一下“Range”列,那正是我试图在dataframe中复制的内容。我找到了matplotlib boxplot,但我不认为我能在数据帧中绘制它们。在

你知道有什么解决办法吗?在


Tags: 数据方法https名称pandaslib绘制公司
2条回答

我不太清楚你到底在找什么,所以如果你还需要什么,请告诉我。在

我使用pandas为图形创建一些虚拟数据和matplotlib。在

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'current':[3,4,7], 'minimum':[1,3,2], 'maximum':[10,14,11], 'average':[8,5,9]})

#   average  current  maximum  minimum
#0        8        3       10        1
#1        5        4       14        3
#2        9        7       11        2

现在是重要的部分。我从图片中重现了你的例子。这个循环迭代数据帧中的每一行,也就是公司。结果就是你有多少个公司就有多少个图表。在

  • ax.plot创建一条从minimum值到 maximum值。在
  • ax.scattercurrentaverage值创建点。在

当然,您必须稍微调整图形,使其看起来像您希望的那样。在

^{pr2}$

这是第一家公司的图表。 enter image description here

编辑(参见@Andrea的评论):将绘制的数据放在一起

您可以按照上面的方法,但调整图形的样式。在

for index,row in df.iterrows(): 
    fig, ax = plt.subplots(figsize=(7, 0.2)) # adjust the width and height of the graphs
    ax.plot([df['minimum'][index],df['maximum'][index]],[0,0],color='gray',zorder=0)      
    ax.scatter(df['current'][index],0,zorder=1)
    ax.scatter(df['average'][index],0,marker='D',zorder=2)   
    plt.xticks([]) # disable the ticks of the x-axis
    plt.yticks([]) # disable the ticks of the y-axis   
    for spine in plt.gca().spines.values(): # disable the border around the graphs
        spine.set_visible(False)

这看起来很接近你在问题中发布的图片。 enter image description here

好的,基于NK_u帮助和内容: Matplotlib- Creating a table with line plots in cells?

我总算把它拼在一起了:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

df = pd.DataFrame({'Name':["A","B","C","E","F"],'current':[3,4,7,6,6], 'minimum':[1,3,2,4,1], 'maximum':[10,14,11,7,10], 'average':[8,5,9,5,3]})


data = np.random.rand(100,5)
col1 = df["Name"]
col2 = df["current"]
col2colors = ["red", "g", "r", "r", "r"]
col3 = df["average"]
finalsc = "D+"

fig, axes = plt.subplots(ncols=5, nrows=5, figsize=(6,2.6),
                         gridspec_kw={"width_ratios":[1,1,1,3,3]})
fig.subplots_adjust(0.05,0.05,0.95,0.95, wspace=0.02, hspace=0.05)   #wspace, hspace  > bordi interni grigi della tabella

for ax in axes.flatten():
    ax.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0)
    ax.ticklabel_format(useOffset=False, style="plain")
    for _,s in ax.spines.items():
        s.set_visible(True)

border = fig.add_subplot(111)
border.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0)
border.set_facecolor("None")

text_kw = dict(ha="center", va="bottom", size=15)
for i,ax in enumerate(axes[:,0]):
    ax.text(0.5, 0.2, col1[i], transform=ax.transAxes, **text_kw)

for i,ax in enumerate(axes[:,1]):
    ax.text(0.5, 0.2, "{:.2f}".format(col2[i]),transform=ax.transAxes, **text_kw)
    ax.set_facecolor(col2colors[i])
    ax.patch.set_color(col2colors[i])

for i,ax in enumerate(axes[:,2]):
    ax.text(0.5, 0.2, "{:.2f}".format(col3[i]),transform=ax.transAxes, **text_kw)

for i,ax in enumerate(axes[:,3]):
    ax.plot(data[:,i], color="green", linewidth=1)

for i,ax in enumerate(axes[:,4]):
    ax.plot([df['minimum'][index],df['maximum'][index]],[0,0],zorder=0)      
    ax.scatter(df['current'][index],0,zorder=1)
    ax.scatter(df['average'][index],0,zorder=2)

plt.show()

老实说,我不知道我编写的代码是否是我可以使用的最好的代码,有许多部分我还需要理解。在

最后一个问题是: 有人能帮我在这张表上加上第一行,用粗体显示每一列的标题吗? 谢谢

相关问题 更多 >