python 图表制作及功能化,python绘制可视化图表

本文详细介绍了如何使用Python进行数据可视化,包括条形图、分组和堆叠条形图、直方图、箱线图以及如何定制各种图表的样式,如颜色、线宽和图例。使用了matplotlib和seaborn库进行示例演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家好,小编来为大家解答以下问题,python数据可视化之美:专业图表绘制指南(全彩),python可视化图表和excel的区别,现在让我们一起来看看吧!

Source code download: 本文相关源码

大家好,小编来为大家解答以下问题,python可视化图做好了怎么弄下来,python做可视化数据图表,现在让我们一起来看看吧!

1.条形图

以下示例显示如何在条形图上显示每组的观测值数。matplotlib 的 bar() 函数用于使用以下参数绘制 barplot:

x :条形的 x 坐标python编程代码复制python自动化运维系统
高度 : 条形的高度。
宽度 : 条形的宽度。
颜色 :条形图面的颜色。
标签 :条形的标签。
请注意,legend() 函数用于添加图例,xticks() 函数用于将柱线标签添加到 x 轴,text() 函数用于在每个柱线顶部添加文本。

如果您需要在每个条形图的顶部添加观测值的数量,则意味着每组有多个观测值。在这种情况下,条形图可能不是可视化数据的最合适方法!事实上,每个条形背后的所有信息都丢失了。

您可能应该尝试使用小提琴图或箱线图。另一种解决方案是在每个条形的顶部添加误差线。

# library
import matplotlib.pyplot as plt
 
# Create bars
barWidth = 0.9
bars1 = [3, 3, 1]
bars2 = [4, 2, 3]
bars3 = [4, 6, 7, 10, 4, 4]
bars4 = bars1 + bars2 + bars3
 
# The X position of bars
r1 = [1,5,9]
r2 = [2,6,10]
r3 = [3,4,7,8,11,12]
r4 = r1 + r2 + r3
 
# Create barplot
plt.bar(r1, bars1, width = barWidth, color = (0.3,0.1,0.4,0.6), label='Alone')
plt.bar(r2, bars2, width = barWidth, color = (0.3,0.5,0.4,0.6), label='With Himself')
plt.bar(r3, bars3, width = barWidth, color = (0.3,0.9,0.4,0.6), label='With other genotype')
# Note: the barplot could be created easily. See the barplot section for other examples.
 
# Create legend
plt.legend()
 
# Text below each barplot with a rotation at 90°
plt.xticks([r + barWidth for r in range(len(r4))], ['DD', 'with himself', 'with DC', 'with Silur', 'DC', 'with himself', 'with DD', 'with Silur', 'Silur', 'with himself', 'with DD', 'with DC'], rotation=90)
 
# Create labels
label = ['n = 6', 'n = 25', 'n = 13', 'n = 36', 'n = 30', 'n = 11', 'n = 16', 'n = 37', 'n = 14', 'n = 4', 'n = 31', 'n = 34']
 
# Text on the top of each bar
for i in range(len(r4)):
    plt.text(x = r4[i]-0.5 , y = bars4[i]+0.1, s = label[i], size = 6)

# Adjust the margins
plt.subplots_adjust(bottom= 0.2, top = 0.98)
 
# Show graphic
plt.show()

2.分组条形图

您可以使用 matplotlib 的 bar() 函数绘制分组条形图。以下示例显示 5 个不同的组及其 3 个变量。为此,变量的值和位置被传递给 3 个 bar() 函数。

请注意,如果要将图形转换为堆叠区域条形图,可以查看以下帖子。

# libraries
import numpy as np
import matplotlib.pyplot as plt
 
# set width of bars
barWidth = 0.25
 
# set heights of bars
bars1 = [12, 30, 1, 8, 22]
bars2 = [28, 6, 16, 5, 10]
bars3 = [29, 3, 24, 25, 17]
 
# Set position of bar on X axis
r1 = np.arange(len(bars1))
r2 = [x + barWidth for x in r1]
r3 = [x + barWidth for x in r2]
 
# Make the plot
plt.bar(r1, bars1, color='#7f6d5f', width=barWidth, edgecolor='white', label='var1')
plt.bar(r2, bars2, color='#557f2d', width=barWidth, edgecolor='white', label='var2')
plt.bar(r3, bars3, color='#2d7f5e', width=barWidth, edgecolor='white', label='var3')
 
# Add xticks on the middle of the group bars
plt.xlabel('group', fontweight='bold')
plt.xticks([r + barWidth for r in range(len(bars1))], ['A', 'B', 'C', 'D', 'E'])
 
# Create legend & Show graphic
plt.legend()
plt.show()

 3.堆叠条形图

在堆叠条形图中,子组彼此重叠显示。该代码与上一篇文章#11分组条形图非常相似。您将为每个变量传递相同的位置,而不是将不同的 x 轴位置传递给函数。此外,为了在彼此之上绘制柱线,您应该使用 bar() 函数的底部参数。此参数将设置柱线的底值(底线)。

在下面的帖子 #13 中,您可以看到如何轻松地将此图转换为堆叠的百分比条形图。

# libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
 
# y-axis in bold
rc('font', weight='bold')
 
# Values of each group
bars1 = [12, 28, 1, 8, 22]
bars2 = [28, 7, 16, 4, 10]
bars3 = [25, 3, 23, 25, 17]
 
# Heights of bars1 + bars2
bars = np.add(bars1, bars2).tolist()
 
# The position of the bars on the x-axis
r = [0,1,2,3,4]
 
# Names of group and bar width
names = ['A','B','C','D','E']
barWidth = 1
 
# Create brown bars
plt.bar(r, bars1, color='#7f6d5f', edgecolor='white', width=barWidth)
# Create green bars (middle), on top of the first ones
plt.bar(r, bars2, bottom=bars1, color='#557f2d', edgecolor='white', width=barWidth)
# Create green bars (top)
plt.bar(r, bars3, bottom=bars, color='#2d7f5e', edgecolor='white', width=barWidth)
 
# Custom X axis
plt.xticks(r, names, fontweight='bold')
plt.xlabel("group")
 
# Show graphic
plt.show()

4.直方图

在直方图顶部添加箱线图可以帮助您更好地了解数据的分布并可视化异常值和四分位数位置。请注意,我们选择使用下面的 histplot 函数,尽管您肯定也可以使用 distplot 函数。

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above) 
sns.set(style="darkgrid")
df = sns.load_dataset("iris")
 
# creating a figure composed of two matplotlib.Axes objects (ax_box and ax_hist)
f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw={"height_ratios": (.15, .85)})
 
# assigning a graph to each ax
sns.boxplot(df["sepal_length"], ax=ax_box)
sns.histplot(data=df, x="sepal_length", ax=ax_hist)
 
# Remove x axis name for the boxplot
ax_box.set(xlabel='')
plt.show()

5. 在同一图上绘制分布

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above) 
sns.set(style="darkgrid")
df = sns.load_dataset("iris")

sns.histplot(data=df, x="sepal_length", color="skyblue", label="Sepal Length", kde=True)
sns.histplot(data=df, x="sepal_width", color="red", label="Sepal Width", kde=True)

plt.legend() 
plt.show()

根据需要将图形分割成尽可能多的轴

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above) 
sns.set(style="darkgrid")
df = sns.load_dataset("iris")

fig, axs = plt.subplots(2, 2, figsize=(7, 7))

sns.histplot(data=df, x="sepal_length", kde=True, color="skyblue", ax=axs[0, 0])
sns.histplot(data=df, x="sepal_width", kde=True, color="olive", ax=axs[0, 1])
sns.histplot(data=df, x="petal_length", kde=True, color="gold", ax=axs[1, 0])
sns.histplot(data=df, x="petal_width", kde=True, color="teal", ax=axs[1, 1])

plt.show()

 6.二维条形图

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above) 
sns.set(style="darkgrid")
df = sns.load_dataset("iris")

sns.histplot(data=df, y="sepal_length")
plt.show()

 7.直方图 + 地毯 + 核密度曲线

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above) 
sns.set(style="darkgrid")
df = sns.load_dataset("iris")

sns.distplot(df["sepal_length"], kde=True, rug=True)
# in the next version of the distplot function, one would have to write:
# sns.distplot(data=df, x="sepal_length", kde=True, rug=True) # note that 'kind' is 'hist' by default
plt.show()

 定制地毯

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above) 
sns.set(style="darkgrid")
df = sns.load_dataset("iris")

sns.distplot(df["sepal_length"],
             kde=True,
             rug=True,
             rug_kws={"color": "r", "alpha": 0.3, "linewidth": 2, "height":0.2})
# in the next version of the distplot function, one would have to write:
# sns.distplot(data=df, x="sepal_length", kde=True, rug=True, rug_kws={"color": "r", "alpha":0.3, "linewidth": 2, "height":0.2 })
plt.show()

 自定义密度曲线

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
# set a grey background (use sns.set_theme() if seaborn version 0.11.0 or above) 
sns.set(style="darkgrid")
df = sns.load_dataset("iris")

sns.distplot(df["sepal_length"],
             kde=True,
             kde_kws={"color": "g", "alpha": 0.3, "linewidth": 5, "shade": True})
# in the next version of the distplot function, one would have to write:
# sns.distplot(data=df, x="sepal_length", kde=True, kde_kws={"color": "g", "alpha": 0.3, "linewidth": 5, "shade": True})
plt.show()

 8.使用 RGB 的统一颜色

# libraries
import numpy as np
import matplotlib.pyplot as plt
 
# create a dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))

# Create bars
plt.bar(x_pos, height, color=(0.2, 0.4, 0.6, 0.6))

# Create names on the x-axis
plt.xticks(x_pos, bars)

# Show graph
plt.show()

 每个条形的不同颜色

# libraries
import numpy as np
import matplotlib.pyplot as plt
 
# create a dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))

# Create bars with different colors
plt.bar(x_pos, height, color=['black', 'red', 'green', 'blue', 'cyan'])

# Create names on the x-axis
plt.xticks(x_pos, bars)

# Show graph
plt.show()

 控制边框的颜色

# libraries
import numpy as np
import matplotlib.pyplot as plt
 
# create a dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))

# Create bars with blue edge color
plt.bar(x_pos, height, color=(0.1, 0.1, 0.1, 0.1),  edgecolor='blue')

# Create names on the x-axis
plt.xticks(x_pos, bars)

# Show graph
plt.show()

9. 自定义线宽

# libraries & dataset
import seaborn as sns
import matplotl

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值