40个python代码可视化实践案例

关于我自己都看不懂的40个代码

一. 柱形图

# Libraries
import numpy as np
import matplotlib.pyplot as plt
 
# Create 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)
 
# Create names on the x-axis
plt.xticks(x_pos, bars)
 
# Show graphic
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ebdBfqD7-1685958225983)(output_2_0.png)]

二. 三色柱形图

# 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()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yUJ46pbm-1685958225984)(output_4_0.png)]

三. 叠加柱形图

# 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()
在这里插入图片描述

在这里插入图片描述

四. 叠加百分比柱形图

# libraries
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
 
# Data
r = [0,1,2,3,4]
raw_data = {
   'greenBars': [20, 1.5, 7, 10, 5], 'orangeBars': [5, 15, 5, 10, 15],'blueBars': [2, 15, 18, 5, 10]}
df = pd.DataFrame(raw_data)
 
# From raw value to percentage
totals = [i+j+k for i,j,k in zip(df['greenBars'], df['orangeBars'], df['blueBars'])]
greenBars = [i / j * 100 for i,j in zip(df['greenBars'], totals)]
orangeBars = [i / j * 100 for i,j in zip(df['orangeBars'], totals)]
blueBars = [i / j * 100 for i,j in zip(df['blueBars'], totals)]
 
# plot
barWidth = 0.85
names = ('A','B','C','D','E')
# Create green Bars
plt.bar(r, greenBars, color='#b5ffb9', edgecolor='white', width=barWidth)
# Create orange Bars
plt.bar(r, orangeBars, bottom=greenBars, color='#f9bc86', edgecolor='white', width=barWidth)
# Create blue Bars
plt.bar(r, blueBars, bottom=[i+j for i,j in zip(greenBars, orangeBars)], color='#a3acff', edgecolor='white', width=barWidth)
 
# Custom x axis
plt.xticks(r, names)
plt.xlabel("group")
 
# Show graphic
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d8HCvmyP-1685958225985)(output_8_0.png)]

五. 叠加百分比柱形图

# 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()

六. 紫色柱形图

# libraries
import numpy as np
import matplotlib.pyplot as plt
 
# create dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))
 
# Create bars and choose color
plt.bar(x_pos, height, color = (0.5,0.1,0.5,0.6))
 
# Add title and axis names
plt.title('My title')
plt.xlabel('categories')
plt.ylabel('values')
 
# Create names on the x axis
plt.xticks(x_pos, bars)
 
# Show graph
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JndYghas-1685958225985)(output_12_0.png)]

七.带条纹的条形图

# Libraries
import numpy as np
import matplotlib.pyplot as plt
 
# Create dataset
height = [2, 5, 4, 6]
bars = ('A', 'B', 'C', 'D')
x_pos = np.arange(len(bars))
 
# Create bars
figure = plt.bar(x_pos, height)

# Define some hatches
hatches = ['-', '/', '||', '///']

# Loop over bars and assign hatches
for bar, hatch in zip(figure, hatches):
    bar.set_hatch(hatch)

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-34iZUXxi-1685958225986)(output_14_0.png)]

八、带标签的不同色条形图

# libraries
import numpy as np
import matplotlib.pyplot as plt
 
# width of the bars
barWidth = 0.3
 
# Choose the height of the blue bars
bars1 = [10, 9, 2]
 
# Choose the height of the cyan bars
bars2 = [10.8, 9.5, 4.5]
 
# Choose the height of the error bars (bars1)
yer1 = [0.5, 0.4, 0.5]
 
# Choose the height of the error bars (bars2)
yer2 = [1, 0.7, 1]
 
# The x position of bars
r1 = np.arange(len(bars1))
r2 = [x + barWidth for x in r1]
 
# Create blue bars
plt.bar(r1, bars1, width = barWidth, color = 'blue', edgecolor = 'black', yerr=yer1, capsize=7, label='poacee')
 
# Create cyan bars
plt.bar(r2, bars2, width = barWidth, color = 'cyan', edgecolor = 'black', yerr=yer2, capsize=7, label='sorgho')
 
# general layout
plt.xticks([r + barWidth for r in range(len(bars1))], ['cond_A', 'cond_B', 'cond_C'])
plt.ylabel('height')
plt.legend()
 
# Show graphic
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5xrxjY21-1685958225986)(output_16_0.png)]

九、详细的条形图

# 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 =
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
当今Python中最流行的数据可视化库是 Matplotlib 和 Seaborn。Matplotlib是一个功能强大的绘图库,可以创建各种类型的图表,而 Seaborn 则是基于 Matplotlib 的高级数据可视化库,提供了更简单、更美观的绘图风格以及更多的统计图表。 下面是一些 Python 数据可视化分析案例的详解: 1. 折线图 折线图是一种经典的数据可视化方式,可以用于表示随时间变化的数据。下面是一个使用 Matplotlib 绘制折线图的例子: ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [3, 7, 2, 5, 9] plt.plot(x, y) plt.show() ``` 上述代码将绘制一个简单的折线图,横坐标是 x 列表,纵坐标是 y 列表。 2. 散点图 散点图是一种用于表示两个变量之间关系的方式,通常用于探索数据中的趋势和异常值。下面是一个使用 Seaborn 绘制散点图的例子: ```python import seaborn as sns tips = sns.load_dataset("tips") sns.scatterplot(x="total_bill", y="tip", data=tips) ``` 上述代码将绘制一个餐厅账单和小费之间的散点图,横坐标是账单总金额,纵坐标是小费金额。 3. 直方图 直方图是一种用于表示连续变量分布的方式,通常用于了解数据的分布情况。下面是一个使用 Matplotlib 绘制直方图的例子: ```python import matplotlib.pyplot as plt import numpy as np data = np.random.randn(1000) plt.hist(data, bins=30) plt.show() ``` 上述代码将绘制一个随机生成的数据集的直方图,bin 参数指定直方图的柱数。 4. 箱线图 箱线图是一种用于表示数据分布和异常值的方式,通常用于比较多个组之间的差异。下面是一个使用 Seaborn 绘制箱线图的例子: ```python import seaborn as sns tips = sns.load_dataset("tips") sns.boxplot(x="day", y="total_bill", data=tips) ``` 上述代码将绘制一个表示不同周几账单总金额分布情况的箱线图。 5. 热力图 热力图是一种用于表示数据密度的方式,通常用于探索数据的相关性。下面是一个使用 Seaborn 绘制热力图的例子: ```python import seaborn as sns flights = sns.load_dataset("flights").pivot("month", "year", "passengers") sns.heatmap(flights, annot=True, fmt="d", cmap="YlGnBu") ``` 上述代码将绘制一个表示航班乘客数量的热力图,横坐标是年份,纵坐标是月份。 以上是一些 Python 数据可视化分析的例子,您可以根据具体需求选择不同的图表类型和绘图库。同时,这些例子只是入门级别,数据可视化的应用场景非常广泛,您可以在实践中不断发掘更多的用法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值