如何使用matplotlib在DataFrame中创建数据分组条形图

2024-06-25 22:41:16 发布

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

这是我当前的输出: enter image description here 现在,我希望在已绘制的条形图旁边显示下一条条形图

我的数据帧有3列:“块”、“簇”和“区”

“块”和“簇”包含用于打印的数字,分组基于 关于“地区”中的字符串

如何在现有条形图旁边绘制其他条形图?

df=pd.read_csv("main_ds.csv")
fig = plt.figure(figsize=(20,8))
ax = fig.add_subplot(111)
plt.xticks(rotation=90)
bwidth=0.30
indic1=ax.bar(df["District"],df["Block"], width=bwidth, color='r')
indic2=ax.bar(df["District"],df["Cluster"], width=bwidth, color='b')
ax.autoscale(tight=False)

def autolabel(rects):
    for rect in rects:
        h = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
                ha='center', va='top')
autolabel(indic1)
autolabel(indic2)
plt.show()

数据:

地区街区集群村庄学校十年增长率识字率男性识字率女性识字率小学。。。政府学校学校学校政府学校农村学校农村政府学校招生政府学校招生农村学校教师 0迪马普尔53027849423.285.488.182.5147。。。298 196 242 90 33478 57176 21444 18239 3701 3571 基菲尔3394142-58.473.176.570.471。。。118 24 118 24 5947 7123 5947 7123 853 261 2 Kohima 5 5 121 290 22.7 85.6 89.3 81.6 128。。。189 101 157 49 10116 26464 5976 8450 2068 2193 3龙岭2 37 113-30.5 71.1 75.6 65.4 60。。。90 23 90 23 3483 4005 3483 4005 830 293 4星期一5 139 309-3.8 56.6 60.4 52.4 165。。。231 78 219 58 18588 16578 17108 8665 1667 903 5行×26列


Tags: 数据rectdfget绘制pltaxwidth
2条回答

试着改变

indic1=ax.bar(df["District"],df["Block"], width=bwidth, color='r')
indic2=ax.bar(df["District"],df["Cluster"], width=bwidth, color='b')

indic1=ax.bar(df["District"]-bwidth/2,df["Block"], width=bwidth, color='r')
indic2=ax.bar(df["District"]+bwidth/2,df["Cluster"], width=bwidth, color='b')

尝试使用pandas.DataFrame.plot

import pandas as pd
import numpy as np
from io import StringIO
from datetime import date
import matplotlib.pyplot as plt

def add_value_labels(ax, spacing=5):
    for rect in ax.patches:
        y_value = rect.get_height()
        x_value = rect.get_x() + rect.get_width() / 2

        space = spacing
        # Vertical alignment for positive values
        va = 'bottom'

        # If value of bar is negative: Place label below bar
        if y_value < 0:
            # Invert space to place label below
            space *= -1
            # Vertically align label at top
            va = 'top'

        # Use Y value as label and format number with one decimal place
        label = "{:.1f}".format(y_value)

        # Create annotation
        ax.annotate(
            label,                      # Use `label` as label
            (x_value, y_value),         # Place label at end of the bar
            xytext=(0, space),          # Vertically shift label by `space`
            textcoords="offset points", # Interpret `xytext` as offset in points
            ha='center',                # Horizontally center label
            va=va)                      # Vertically align label differently for
                                        # positive and negative values.

first3columns = StringIO("""District    Block   Cluster
Dimapur 5   30
Kiphire 3   3
Kohima  5   5
Longleng    2
Mon 5   5
""")

df_plot = pd.read_csv(first3columns, delim_whitespace=True)


fig, ax = plt.subplots()


#df_plot.set_index(['District'], inplace=True)
df_plot[['Block', 'Cluster']].plot.bar(ax=ax, color=['r', 'b'])
ax.set_xticklabels(df_plot['District'])

add_value_labels(ax)

plt.show()

enter image description here

相关问题 更多 >