21040301206郭怀庆

章若楠看到都得点赞的python可视化图形代码

csdn:https://blog.csdn.net/qq_65756462/article/details/131052860?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22131052860%22%2C%22source%22%3A%22qq_65756462%22%7D

1柱状图

这个例子可能展示了您可以使用python和matplotlib完成的最基本的条形图。
bar()函数与以下参数一起使用:
x:条的x坐标。(示例中的x_pos)
高度:杆的高度。

# 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-VShEmT1D-1685959666329)(output_2_0.png)]

2柱状图

下面的示例展示了如何在barplot上显示每组的观察数。matplotlib的Bar()函数用于绘制barplot,参数如下:

x:条的x坐标。

高度:杆的高度。

宽度:条的宽度。

颜色:条面颜色。

标签:棒材的标签。

注意,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()

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

3散点图

你可以在以下的情节中选择调色板。

-调色板有三种类型:顺序的、离散的和发散的。您可以在下面的部分中找到每个类别的解释和示例。

顺序

当您将值从相对低映射到高或从高映射到低时,顺序调色板是合适的。为了在顺序调色板中设置颜色从浅到深,您应该在绘图函数中提供调色板参数。如果你想要颜色的相反顺序(从深到浅),你可以简单地在你选择的颜色后面加上后缀“_r”。

# Libraries
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# create data
x = np.random.rand(80) - 0.5
y = x+np.random.rand(80)
z = x+np.random.rand(80)
df = pd.DataFrame({'x':x, 'y':y, 'z':z})
 
# Plot with palette
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="Blues")
plt.show()
 
# reverse palette
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="Blues_r")
plt.show()

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

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

4发散

当数据集中的高值和低值同样重要时,使用发散的调色板是合适的。发散色由两种对比色组成,边缘较暗,中心较亮。您可以通过在您选择的颜色后添加后缀“_r”来使用反向颜色。

# Libraries
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# create data
x = np.random.rand(80) - 0.5
y = x+np.random.rand(80)
z = x+np.random.rand(80)
df = pd.DataFrame({'x':x, 'y':y, 'z':z})
 
# plot
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="PuOr")
plt.show()

# reverse palette
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="PuOr_r")
plt.show()

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

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

5离散

您可以使用seaborn的set_palette()函数来控制颜色。可以将想要在绘图中使用的颜色列表作为set_palette函数的参数。

# library & dataset
import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset(name="iris",cache=True,data_home="/Users/86134/seaborn-data-master")

# use the 'palette' argument of seaborn
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False, hue='species', legend=False, palette="Set1")
plt.legend(loc='lower right')
plt.show()
 
# use a handmade palette
flatui = ["#9b59b6", "#3498db", "orange"]
sns.set_palette(flatui)
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False, hue='species', legend=False)
plt.show()

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

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

6K线图

Seaborn python库以其灰色背景和通用样式而闻名。然而,很少有其他内置风格可用:暗网格,白网格,深色,白色和刻度。您可以使用seaborn库的set_style()函数设置主题。

# libraries
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
 
# Data
data = np.random.normal(size=(20, 6)) + np.arange(6) / 2
 
# Proposed themes: darkgrid, whitegrid, dark, white, and ticks
 
sns.set_style("whitegrid")
sns.boxplot(data=data)
plt.title("whitegrid")
plt.show()
 
sns.set_style("darkgrid")
sns.boxplot(data=data);
plt.title("darkgrid")
plt.show()
 
sns.set_style("white")
sns.boxplot(data=data);
plt.title("white")
plt.show()

sns.set_style("dark")
sns.boxplot(data=data);
plt.title("dark")
plt.show()

sns.set_style("ticks")
sns.boxplot(data=data);
plt.title("ticks")
plt.show()

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

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

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

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

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

7折线图

Matplotlib允许你制作任何类型的图表。然而,matplotlib库的图表风格不像seaborn风格那么花哨。在matplotlib中绘制图表时,可以受益于seaborn库风格。您只需要加载seaborn库并使用seaborn set_theme()函数!

# library and dataset
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
 
# Create data
df=pd.DataFrame({'x_axis': range(1,101), 'y_axis': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })
 
# plot with matplotlib
plt.plot( 'x_axis', 'y_axis', data=df, marker='o', color='mediumvioletred')
plt.show()

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

# library and dataset
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
 
# Create data
df=pd.DataFrame({'x_axis': range(1,101), 'y_axis': np.random.randn(100)*15+range(1,101), 'z': (np.random.randn(100)*15+range(1,101))*2 })

# Just load seaborn & set theme and the chart looks better:
import seaborn as sns
sns.set_theme()

# Plot
plt.plot( 'x_axis', 'y_axis', data=df, marker='o', color='mediumvioletred')
plt.show()

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

8柱状图

您可以使用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()

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

9堆叠柱状图

在堆叠条形图中,子组显示在彼此的顶部。您将为每个变量传递相同的位置,而不是传递不同的x轴位置给函数。此外,为了在彼此的顶部绘制条,您应该使用bar()函数的bottom参数。此参数将设置条的底部值(底线)。

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

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

10折线图

您可以使用matplotlib库的plot()函数创建一个基本的折线图。如果您只给出一系列值,matplotlib将考虑这些值是有序的,并将使用从1到n的值来创建X轴(图1):

# libraries
import matplotlib.pyplot as plt
import numpy as np
 
# create data
values=np.cumsum(np.random.randn(1000,1))
 
# use the plot function
plt.plot(values)

# show the graph
plt.show()

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

11折线图

为了获得更时髦的外观,您可以使用seaborn库的set_theme()函数。您将自动获得图2所示的外观。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
 
# use seaborn style
sns.set_theme()

# create data
values=np.cumsum(np.random.randn(1000,1))
 
# use the plot function
plt.plot(values)

# show the graph
plt.show()

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

12折线图

对无序数据使用lineplot

你也可以用两个系列的值(X轴和Y轴)制作折线图。但是,请确保您的X轴值是有序的!如果不是,您将得到这样的图(图3)。

# libraries
import matplotlib.pyplot as plt
import seaborn as sns
 
# import the iris dataset
df = sns.load_dataset(name="iris",cache=True,data_home="/Users/86134/seaborn-data-master")
 
# plot
plt.plot( 'sepal_width', 'sepal_length', data=df)

# show the graph
plt.show()

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

13折线图

对有序数据使用lineplot

如果您的X数据是有序的,那么您将得到与图1类似的图:

# libraries and data
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
df=pd.DataFrame({'xvalues': range(1,101), 'yvalues': np.random.randn(100) })
 
# plot
plt.plot( 'xvalues', 'yvalues', data=df)

# show the graph
plt.show()

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

14折线图

自定义线条颜色

要自定义颜色,只需使用color参数!

请注意,您可以使用alpha参数为颜色添加透明度(0=transparent, 1=opaque)。

# Libraries and data
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.DataFrame({'x_values': range(1,11), 'y_values': np.random.randn(10) })

# Draw plot
plt.plot( 'x_values', 'y_values', data=df, color='skyblue')
plt.show()

# Draw line chart by modifiying transparency of the line
plt.plot( 'x_values', 'y_values', data=df, color='skyblue', alpha=0.3)

# Show plot
plt.show()

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

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

15折线图

自定义行样式

可以使用linestyle参数在不同的行样式之间进行选择。

# Libraries and data
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.DataFrame({'x_values': range(1,11), 'y_values': np.random.randn(10) })

# Draw line chart with dashed line
plt.plot( 'x_values', 'y_values', data=df, linestyle='dashed')

# Show graph
plt.show()

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

16线条图

下面的例子展示了不同类型的线条样式。

plt.plot( [1,1.1,1,1.1,1], linestyle='-' , linewidth=4)
plt.text(1.5, 1.3, "linestyle = '-' ", horizontalalignment='left', size='medium', color='C0', weight='semibold')
plt.plot( [2,2.1,2,2.1,2], linestyle='--' , linewidth=4 )
plt.text(1.5, 2.3, "linestyle = '--' ", horizontalalignment='left', size='medium', color='C1', weight='semibold')
plt.plot( [3,3.1,3,3.1,3], linestyle='-.' , linewidth=4 )
plt.text(1.5, 3.3, "linestyle = '-.' ", horizontalalignment='left', size='medium', color='C2', weight='semibold')
plt.plot( [4,4.1,4,4.1,4], linestyle=':' , linewidth=4 )
plt.text(1.5, 4.3, "linestyle = ':' ", horizontalalignment='left', size='medium', color='C3', weight='semibold')
plt.axis('off')
plt.show()

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

17线条图

自定义线宽

您还可以使用linewidth参数自定义线宽。

# Libraries and data
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.DataFrame({'x_values': range(1,11), 'y_values': np.random.randn(10) })

# Modify line width of the graph
plt.plot( 'x_values', 'y_values', data=df, linewidth=22)

# Show graph
plt.show()

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

18折线图

这个例子展示了如何用几条线制作折线图。每行表示一组值,例如每组一组值。为了使用matplotlib,我们只需要多次调用plot函数(每组调用一次)。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# Data
df=pd.DataFrame({'x_values': range(1,11), 'y1_values': np.random.randn(10), 'y2_values': np.random.randn(10)+range(1,11), 'y3_values': np.random.randn(10)+range(11,21) })
 
# multiple line plots
plt.plot( 'x_values', 'y1_values', data=df, marker='o', markerfacecolor='blue', markersize=12, color='skyblue', linewidth=4)
plt.plot( 'x_values', 'y2_values', data=df, marker='', color='olive', linewidth=2)
plt.plot( 'x_values', 'y3_values', data=df, marker='', color='olive', linewidth=2, linestyle='dashed', label="toto")

# show legend
plt.legend()

# show graph
plt.show()

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

19折线图

突出特定组的技巧是首先用细而谨慎的线条绘制所有组。然后,重新绘制有趣的组(s)与强烈的和真正可见的线。此外,最好使用自定义注释来注释这个突出显示的组。下面的示例展示了如何通过使用matplotlib的plot()函数的颜色、线宽和alpha参数来实现这一点。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# Make a data frame
df=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14) })

# Change the style of plot
plt.style.use('seaborn-darkgrid')

# set figure size
my_dpi=96
plt.figure(figsize=(480/my_dpi, 480/my_dpi), dpi=my_dpi)
 
# plot multiple lines
for column in df.drop('x', axis=1):
    plt.plot(df['x'], df[column], marker='', color='grey', linewidth=1, alpha=0.4)

# Now re do the interesting curve, but biger with distinct color
plt.plot(df['x'], df['y5'], marker='', color='orange', linewidth=4, alpha=0.7)
 
# Change x axis limit
plt.xlim(0,12)
 
# Let's annotate the plot
num=0
for i in df.values[9][1:]:
    num+=1
    name=list(df)[num]
    if name != 'y5':
        plt.text(10.2, i, name, horizontalalignment='left', size='small', color='grey')

# And add a special annotation for the group we are interested in
plt.text(10.2, df.y5.tail(1), 'Mr Orange', horizontalalignment='left', size='small', color='orange')
 
# Add titles
plt.title("Evolution of Mr Orange vs other students", loc='left', fontsize=12, fontweight=0, color='orange')
plt.xlabel("Time")
plt.ylabel("Score")

# Show the graph
plt.show()

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

20 意面图

表示这些数据的其他方法

突出显示组

假设你画了很多组,但真正的原因是为了解释一个特定组与其他组相比的特征。

一个好的做法是突出显示这个组:使它看起来不同,并给它一个适当的注释。在这里,橙色线的行为是显而易见的。

查看这里的代码。

使用小倍数

如果你对所有组都感兴趣,那么一个好的解决方案就是将它们分成单独的子图。正如你在这里看到的,每个群体的行为都比意大利面条图更容易读懂。

在这里查看这个版本的代码。

小倍数(变种)

另一种选择是做同样的事情,但在每个子图上分别显示所有组。这取决于你选择你喜欢的版本。下面是代码。

面积图

如果您决定使用小倍数,我个人倾向于使用面积图而不是线形图。我觉得在面积图中更容易看到趋势,但这只是我个人的观点。

无论如何,这是这个图表的代码。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# Make a data frame
df=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14), 'y9': np.random.randn(10)+range(4,14), 'y10': np.random.randn(10)+range(2,12) })
 
# Change the style of plot
plt.style.use('seaborn-darkgrid')
 
# Create a color palette
palette = plt.get_cmap('Set1')
 
# Plot multiple lines
num=0
for column in df.drop('x', axis=1):
    num+=1
    plt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=1, alpha=0.9, label=column)

# Add legend
plt.legend(loc=2, ncol=2)
 
# Add titles
plt.title("A (bad) Spaghetti plot", loc='left', fontsize=12, fontweight=0, color='orange')
plt.xlabel("Time")
plt.ylabel("Score")

# Show the graph
plt.show()

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

21意面图

有几种方法可以避免产生意大利面图,其中一种是使用小倍数:在这里,我们在几个子图中切割窗口,每个组一个。然后,您可以选择单独显示每个组,或者根本不显示它们。注意,您可以很容易地对面积图执行相同的操作。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# Make a data frame
df=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14), 'y9': np.random.randn(10)+range(4,14) })
 
# Initialize the figure style
plt.style.use('seaborn-darkgrid')
 
# create a color palette
palette = plt.get_cmap('Set1')
 
# multiple line plot
num=0
for column in df.drop('x', axis=1):
    num+=1
 
    # Find the right spot on the plot
    plt.subplot(3,3, num)
 
    # Plot the lineplot
    plt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=1.9, alpha=0.9, label=column)
 
    # Same limits for every chart
    plt.xlim(0,10)
    plt.ylim(-2,22)
 
    # Not ticks everywhere
    if num in range(7) :
        plt.tick_params(labelbottom='off')
    if num not in [1,4,7] :
        plt.tick_params(labelleft='off')
 
    # Add title
    plt.title(column, loc='left', fontsize=12, fontweight=0, color=palette(num) )

# general title
plt.suptitle("How the 9 students improved\nthese past few days?", fontsize=13, fontweight=0, color='black', style='italic', y=1.02)
 
# Axis titles
plt.text(0.5, 0.02, 'Time', ha='center', va='center')
plt.text(0.06, 0.5, 'Note', ha='center', va='center', rotation='vertical')

# Show the graph
plt.show()

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

22意面图

正确的图

作为前一个示例的替代方案,您可以创建由所有组的线条组成的多个子图,每个子图中只突出显示一个组。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# Make a data frame
df=pd.DataFrame({'x': range(1,11), 'y1': np.random.randn(10), 'y2': np.random.randn(10)+range(1,11), 'y3': np.random.randn(10)+range(11,21), 'y4': np.random.randn(10)+range(6,16), 'y5': np.random.randn(10)+range(4,14)+(0,0,0,0,0,0,0,-3,-8,-6), 'y6': np.random.randn(10)+range(2,12), 'y7': np.random.randn(10)+range(5,15), 'y8': np.random.randn(10)+range(4,14), 'y9': np.random.randn(10)+range(4,14) })
 
# Initialize the figure style
plt.style.use('seaborn-darkgrid')
 
# create a color palette
palette = plt.get_cmap('Set1')
 
# multiple line plot
num=0
for column in df.drop('x', axis=1):
    num+=1
 
    # Find the right spot on the plot
    plt.subplot(3,3, num)
 
    # plot every group, but discrete
    for v in df.drop('x', axis=1):
        plt.plot(df['x'], df[v], marker='', color='grey', linewidth=0.6, alpha=0.3)
 
    # Plot the lineplot
    plt.plot(df['x'], df[column], marker='', color=palette(num), linewidth=2.4, alpha=0.9, label=column)
 
    # Same limits for every chart
    plt.xlim(0,10)
    plt.ylim(-2,22)
 
    # Not ticks everywhere
    if num in range(7) :
        plt.tick_params(labelbottom='off')
    if num not in [1,4,7] :
        plt.tick_params(labelleft='off')
 
    # Add title
    plt.title(column, loc='left', fontsize=12, fontweight=0, color=palette(num) )

# general title
plt.suptitle("How the 9 students improved\nthese past few days?", fontsize=13, fontweight=0, color='black', style='italic', y=1.02)
 
# Axis titles
plt.text(0.5, 0.02, 'Time', ha='center', va='center')
plt.text(0.06, 0.5, 'Note', ha='center', va='center', rotation='vertical')

# Show the graph
plt.show()

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

23条形图

百分比堆叠条形图与堆叠条形图几乎相同。子组显示在彼此的顶部,但数据被规范化以使每个子组的总和为100。

# 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-WFNorVqX-1685959666344)(output_47_0.png)]

24条形图

编辑:在Prakash的评论之后,我建议对这个图表做一点修改,以便添加一个图例。

# Create green Bars
plt.bar(r, greenBars, color='#b5ffb9', edgecolor='white', width=barWidth, label="group A")
# Create orange Bars
plt.bar(r, orangeBars, bottom=greenBars, color='#f9bc86', edgecolor='white', width=barWidth, label="group B")
# Create blue Bars
plt.bar(r, blueBars, bottom=[i+j for i,j in zip(greenBars, orangeBars)], color='#a3acff', edgecolor='white', width=barWidth, label="group C")
 
# Custom x axis
plt.xticks(r, names)
plt.xlabel("group")
 
# Add a legend
plt.legend(loc='upper left', bbox_to_anchor=(1,1), ncol=1)
 
# Show graphic
plt.show()

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

25散点图

这是一个使用Matplotlib的plot()函数制作的基本散点图示例。这些参数被传递给函数:

X:数据点的X轴坐标

Y:数据点的Y轴坐标

数据:带有标记数据的对象

线条样式:每个点之间的线条样式

标记:标记点的样式

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# Create a dataset:
df=pd.DataFrame({'x_values': range(1,101), 'y_values': np.random.randn(100)*15+range(1,101) })
 
# plot
plt.plot( 'x_values', 'y_values', data=df, linestyle='none', marker='o')
plt.show()

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

26散点图

标志形状

只需使用plot()函数的marker参数来定制数据点的形状。下面的代码生成一个星形标记的散点图(左图)。右图显示了python可能提供的形状。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# dataset
df=pd.DataFrame({'x_values': range(1,101), 'y_values': np.random.randn(100)*80+range(1,101) })

# === Left figure:
plt.plot( 'x_values', 'y_values', data=df, linestyle='none', marker='*')
plt.show()
 
# === Right figure:
all_poss=['.','o','v','^','>','<','s','p','*','h','H','D','d','1','','']
 
# to see all possibilities:
# markers.MarkerStyle.markers.keys()
 
# set the limit of x and y axis:
plt.xlim(0.5,4.5)
plt.ylim(0.5,4.5)
 
# remove ticks and values of axis:
plt.xticks([])
plt.yticks([])
#plt.set_xlabel(size=0)
 
# Make a loop to add markers one by one
num=0
for x in range(1,5):
    for y in range(1,5):
        num += 1
        plt.plot(x,y,marker=all_poss[num-1], markerfacecolor='orange', markersize=23, markeredgecolor="black")
        plt.text(x+0.2, y, all_poss[num-1], horizontalalignment='left', size='medium', color='black', weight='semibold')

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

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

27散点图

标志尺寸

要更改标记大小,只需使用markersize参数:

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# dataset
df=pd.DataFrame({'x_values': range(1,101), 'y_values': np.random.randn(100)*80+range(1,101) })

# scatter plot
plt.plot( 'x_values', 'y_values', data=df, linestyle='none', marker='D', markersize=16)
plt.show()

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

28 散点图

标志的颜色

颜色由markerfacecolor和markeredgecolor参数控制。有几种方法来调用颜色,请参阅这个专门的页面了解更多信息。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# dataset
df=pd.DataFrame({'x_values': range(1,101), 'y_values': np.random.randn(100)*80+range(1,101) })

# scatter plot
plt.plot( 'x_values', 'y_values', data=df, linestyle='none', markerfacecolor='skyblue', marker="o", markeredgecolor="black", markersize=16)
plt.show()

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

29 散点图

标记边缘

正如您可以使用markeredgecolor参数控制标记边缘颜色一样,您也可以使用markeredgewidth参数控制标记宽度。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
 
# dataset
df=pd.DataFrame({'x_values': range(1,101), 'y_values': np.random.randn(100)*80+range(1,101) })

# scatter plot
plt.plot( 'x_values', 'y_values', data=df, linestyle='none', marker='D', markersize=16, markeredgecolor="orange", markeredgewidth=5)
plt.show()

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

30折线图

注意,自动生成的图例结合了行和标记。此图例还反映了我们可能应用的任何定制。

# Libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Set figure default figure size
plt.rcParams["figure.figsize"] = (10, 6)
# Create a random number generator for reproducibility
rng = np.random.default_rng(1111)

# Get some random points!
x = np.array(range(10))
y = rng.integers(10, 100, 10)
z = y + rng.integers(5, 20, 10)

plt.plot(x, z, linestyle="-", marker="o", label="Income")
plt.plot(x, y, linestyle="-", marker="o", label="Expenses")
plt.legend()
plt.show()

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

31折线图

自定义线条和标记

plt.plot(
    x, z, ls="--", lw=3, 
    marker="X", markersize=10, markerfacecolor="red", markeredgecolor="black",
    label="Income"
)
plt.plot(
    x, y, ls=":", 
    marker="o", markersize=15, markerfacecolor="None", 
    label="Expenses"
)
plt.legend()
plt.show()

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

32折线图

传奇的调整

如果您只想在图例中使用线或点,则可以将plt.scatter()和plt.plot()组合在一起,为想要包含在图例中的内容提供标签。例如:

plt.scatter(x, z, label="Income")
plt.plot(x, z, ls="--")

plt.scatter(x, y, label="Expenses")
plt.plot(x, y, ls="--")

plt.legend()
plt.show()

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

33折线图

一个组件一个组件地构建连接的散点图也给了我们更大的灵活性来定制我们的图。例如,通过将颜色列表传递给plt.scatter()中的color参数,可以为标记使用不同的颜色。

更多的定制

plt.plot(x, z)
plt.scatter(x, z, color=["red", "black"] * 5, s=80, zorder=10)
plt.show()

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

34散点图

过度绘图是数据可视化中最常见的问题之一。当您的数据集很大时,散点图的点往往会重叠,并且您的图形变得不可读。

使用matplotlib(可以看到下面的代码),用散点图说明了这个问题。乍一看可能会得出X和y之间没有关系的结论。我们将在下面的章节中看到为什么这是一个错误的结论。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
 
# Dataset:
df=pd.DataFrame({'x': np.random.normal(10, 1.2, 20000), 'y': np.random.normal(10, 1.2, 20000), 'group': np.repeat('A',20000) })
tmp1=pd.DataFrame({'x': np.random.normal(14.5, 1.2, 20000), 'y': np.random.normal(14.5, 1.2, 20000), 'group': np.repeat('B',20000) })
tmp2=pd.DataFrame({'x': np.random.normal(9.5, 1.5, 20000), 'y': np.random.normal(15.5, 1.5, 20000), 'group': np.repeat('C',20000) })
df=df.append(tmp1).append(tmp2)
 
# plot
plt.plot( 'x', 'y', "", data=df, linestyle='', marker='o')
plt.xlabel('Value of X')
plt.ylabel('Value of Y')
plt.title('Overplotting looks like that:', loc='left')
plt.show()
C:\Users\86134\AppData\Local\Temp\ipykernel_31660\1354801395.py:11: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
  df=df.append(tmp1).append(tmp2)
C:\Users\86134\AppData\Local\Temp\ipykernel_31660\1354801395.py:14: UserWarning: linestyle is redundantly defined by the 'linestyle' keyword argument and the fmt string "" (-> linestyle='-'). The keyword argument will take precedence.
  plt.plot( 'x', 'y', "", data=df, linestyle='', marker='o')

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

35散点图

让我们来看看如何避免它:

点尺寸

你可以尝试在你的地块上减少标记的大小。这样它们就不会重叠,图案也会更清晰。

# libraries
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
 
# Dataset:
df=pd.DataFrame({'x': np.random.normal(10, 1.2, 20000), 'y': np.random.normal(10, 1.2, 20000), 'group': np.repeat('A',20000) })
tmp1=pd.DataFrame({'x': np.random.normal(14.5, 1.2, 20000), 'y': np.random.normal(14.5, 1.2, 20000), 'group': np.repeat('B',20000) })
tmp2=pd.DataFrame({'x': np.random.normal(9.5, 1.5, 20000), 'y': np.random.normal(15.5, 1.5, 20000), 'group': np.repeat('C',20000) })
df=df.append(tmp1).append(tmp2)

# Plot with small marker size
plt.plot( 'x', 'y', "", data=df, linestyle='', marker='o', markersize=0.7)
plt.xlabel('Value of X')
plt.ylabel('Value of Y')
plt.title('Overplotting? Try to reduce the dot size', loc='left')
plt.show()
C:\Users\86134\AppData\Local\Temp\ipykernel_31660\2806375468.py:11: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
  df=df.append(tmp1).append(tmp2)
C:\Users\86134\AppData\Local\Temp\ipykernel_31660\2806375468.py:14: UserWarning: linestyle is redundantly defined by the 'linestyle' keyword argument and the fmt string "" (-> linestyle='-'). The keyword argument will take precedence.
  plt.plot( 'x', 'y', "", data=df, linestyle='', marker='o', markersize=0.7)

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

36饼图

您可以使用pandas库的plot()函数轻松绘制饼状图。您应该在kind参数中将plot类型传递为’pie’。

也可以绘制多个图。您可以使用具有多个列的数据框来绘制多个图。

请注意,饼图是一种非常不推荐的表示数据的方式。阅读饼图部分的介绍以了解更多信息。

# library
import pandas as pd
import matplotlib.pyplot as plt
 
# --- dataset 1: just 4 values for 4 groups:
df = pd.DataFrame([8,8,1,2], index=['a', 'b', 'c', 'd'], columns=['x'])
 
# make the plot
df.plot(kind='pie', subplots=True, figsize=(8, 8))

# show the plot
plt.show()

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

37饼图

使用matplotlib绘制甜甜圈图的技巧是绘制一个饼状图,并在中间添加一个白色圆圈。为了绘制一个圆,您可以使用matplotlib的circle()函数。在下面的例子中,传递给函数的参数是:

(x,y):圆心

半径:圆的半径

颜色:圆圈的颜色

在本例中,add_artist()函数用于在饼图的轴线上添加白色圆圈。为了获得当前图形上的当前轴实例,使用gca()函数,并且为了获得当前图形,使用gcf()函数。

# library
import matplotlib.pyplot as plt
 
# create data
size_of_groups=[12,11,3,30]
 
# Create a pie plot
plt.pie(size_of_groups)
#plt.show()
 
# add a white circle at the center
my_circle=plt.Circle( (0,0), 0.7, color='white')
p=plt.gcf()
p.gca().add_artist(my_circle)

# show the graph
plt.show()

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

38饼图

为了更改背景颜色,应该在创建饼图之前使用figure()函数创建一个图形,并使用patch.set_facecolor()设置颜色。

# library
import matplotlib.pyplot as plt
 
# Data
names = 'groupA', 'groupB', 'groupC', 'groupD',
size = [12,11,3,30]
 
# create a figure and set different background
fig = plt.figure()
fig.patch.set_facecolor('black')
 
# Change color of text
plt.rcParams['text.color'] = 'white'
 
# Create a circle at the center of the plot
my_circle=plt.Circle( (0,0), 0.7, color='black')
 
# Pieplot + circle on it
plt.pie(size, labels=names)
p=plt.gcf()
p.gca().add_artist(my_circle)
plt.show()

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

39饼图

这段代码提供了一个甜甜圈图,其中包含3个组和每个组的几个子组。你可以使用半径和宽度选项设置2个圆的位置。然后,我们的想法是为每个组分配一个调色板。请注意,此图形的代码远非最佳。如果能创建一个更通用的函数就太好了。如果你有更好的方法,请不要犹豫,留下评论!

# Libraries
import matplotlib.pyplot as plt
 
# Make data: I have 3 groups and 7 subgroups
group_names=['groupA', 'groupB', 'groupC']
group_size=[12,11,30]
subgroup_names=['A.1', 'A.2', 'A.3', 'B.1', 'B.2', 'C.1', 'C.2', 'C.3', 'C.4', 'C.5']
subgroup_size=[4,3,5,6,5,10,5,5,4,6]
 
# Create colors
a, b, c=[plt.cm.Blues, plt.cm.Reds, plt.cm.Greens]
 
# First Ring (outside)
fig, ax = plt.subplots()
ax.axis('equal')
mypie, _ = ax.pie(group_size, radius=1.3, labels=group_names, colors=[a(0.6), b(0.6), c(0.6)] )
plt.setp( mypie, width=0.3, edgecolor='white')
 
# Second Ring (Inside)
mypie2, _ = ax.pie(subgroup_size, radius=1.3-0.3, labels=subgroup_names, labeldistance=0.7, colors=[a(0.5), a(0.4), a(0.3), b(0.5), b(0.4), c(0.6), c(0.5), c(0.4), c(0.3), c(0.2)])
plt.setp( mypie2, width=0.4, edgecolor='white')
plt.margins(0,0)
 
# show it
plt.show()

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

40维恩图

使用matplotlib库制作维恩图有两种主要方法,可以得到相同的结果。

第一种方法是直接将组的大小及其交点传递给venn2()函数。第二种方法是将2组值传递给函数,python将自己计算每个集合的长度(=每个组)和公共值的数量(它们的交集)。

# library
import matplotlib.pyplot as plt
from matplotlib_venn import venn2
 
# First way to call the 2 group Venn diagram:
venn2(subsets = (10, 5, 2), set_labels = ('Group A', 'Group B'))
plt.show()
 
# Second way
venn2([set(['A', 'B', 'C', 'D']), set(['D', 'E', 'F'])])
plt.show()

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

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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值