如何在Python中使用 Matplotlib 注释 Barplot 中的条?
注释意味着在图表中添加注释,说明它代表什么值。当图形缩小或过度填充时,用户从图形中读取值通常会让人厌烦。在本文中,我们将讨论如何使用matplotlib库对在Python中创建的条形图进行注释。
以下是带注释和未带注释的条形图示例:
循序渐进的方法:
- 让我们首先从 Pandas 数据帧绘制简单的图形,现在我们准备好了以下数据帧:
Python3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Name": ["Alex", "Bob", "Clarein", "Dexter"],
"Marks": [45, 23, 78, 65]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Name', 'Marks'])
Python3
# Defining the plotsize
plt.figure(figsize=(8, 6))
# Defining the x-axis, the y-axis and the data
# from where the values are to be taken
plots = sns.barplot(x="Name", y="Marks", data=df)
# Setting the x-acis label and its size
plt.xlabel("Students", size=15)
# Setting the y-axis label and its size
plt.ylabel("Marks Secured", size=15)
# Finallt plotting the graph
plt.show()
Python3
# Defining the plot size
plt.figure(figsize=(8, 8))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Name", y="Marks", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
# x-coordinate: bar.get_x() + bar.get_width() / 2
# y-coordinate: bar.get_height()
# free space to be left to make graph pleasing: (0, 8)
# ha and va stand for the horizontal and vertical alignment
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 8),
textcoords='offset points')
# Setting the label for x-axis
plt.xlabel("Students", size=14)
# Setting the label for y-axis
plt.ylabel("Marks Secured", size=14)
# Setting the title for the graph
plt.title("This is an annotated barplot")
# Finally showing the plot
plt.show()
Python3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Name": ["Alex", "Bob", "Clarein", "Dexter"],
"Marks": [45, 23, 78, 65]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Name', 'Marks'])
# Defining the plot size
plt.figure(figsize=(8, 8))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Name", y="Marks", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
# x-coordinate: bar.get_x() + bar.get_width() / 2
# y-coordinate: bar.get_height()
# free space to be left to make graph pleasing: (0, 8)
# ha and va stand for the horizontal and vertical alignment
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 8),
textcoords='offset points')
# Setting the label for x-axis
plt.xlabel("Students", size=14)
# Setting the label for y-axis
plt.ylabel("Marks Secured", size=14)
# Setting the title for the graph
plt.title("This is an annotated barplot")
# Finally showing the plot
plt.show()
Python3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Language": ["Python", "C++", "Java"],
"Students": [75, 50, 25]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Language', 'Students'])
# Defining the plot size
plt.figure(figsize=(5, 5))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Language", y="Students", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 5),
textcoords='offset points')
# Setting the title for the graph
plt.title("Example 1")
# Finally showing the plot
plt.show()
Python3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Section": ["A", "B", "C", 'D', 'E'],
"Students": [0, 10, 20, 30, 40]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Section', 'Students'])
# Defining the plot size
plt.figure(figsize=(5, 5))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Section", y="Students", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 5),
textcoords='offset points')
# Setting the title for the graph
plt.title("Example 2")
# Finally showing the plot
plt.show()
Python3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Section": ["A", "B", "C", 'D', 'E'],
"Students": [0, 10, 20, 30, 40]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Section', 'Students'])
# Defining the plot size
plt.figure(figsize=(5, 5))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Section", y="Students", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 5),
textcoords='offset points')
# Setting the title for the graph
plt.title("Example 2")
# Finally showing the plot
plt.show()
输出:
- 现在让我们开始使用seaborn库绘制数据框。我们得到以下结果。但是,条形图中的实际值是多少并不是很明显。当相邻地块的值彼此非常接近时,也会出现这种情况。
蟒蛇3
# Defining the plotsize
plt.figure(figsize=(8, 6))
# Defining the x-axis, the y-axis and the data
# from where the values are to be taken
plots = sns.barplot(x="Name", y="Marks", data=df)
# Setting the x-acis label and its size
plt.xlabel("Students", size=15)
# Setting the y-axis label and its size
plt.ylabel("Marks Secured", size=15)
# Finallt plotting the graph
plt.show()
输出:
- 添加注释。我们在这里的策略是遍历所有条形并在所有条形上放置一个文本,以指出该特定条形的值。这里我们将使用 Matplpotlib 的annotate()函数。我们可以在各种场景中找到此函数的各种用途,目前,我们只会在其顶部显示相应条形的值。
我们的步骤将是:
- 遍历条形
- 获取条形的 x 轴位置(x)和宽度(w),这将帮助我们获取文本的 x 坐标,即get_x()+get_width()/2 。
- 文本的 y 坐标(y)可以使用条形的高度找到,即get_height()
- 所以我们有了注释值的坐标即get_x()+get_width()/2, get_height()
- 但这将准确地在条的边界上打印注释,因此为了获得更令人愉悦的注释图,我们使用参数xyplot=(0, 8) 。这里 8 表示将从条形顶部留下的像素。因此,要低于条形线,我们可以使用xy=(0,-8) 。
- 所以我们执行下面的代码来得到带注释的图:
蟒蛇3
# Defining the plot size
plt.figure(figsize=(8, 8))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Name", y="Marks", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
# x-coordinate: bar.get_x() + bar.get_width() / 2
# y-coordinate: bar.get_height()
# free space to be left to make graph pleasing: (0, 8)
# ha and va stand for the horizontal and vertical alignment
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 8),
textcoords='offset points')
# Setting the label for x-axis
plt.xlabel("Students", size=14)
# Setting the label for y-axis
plt.ylabel("Marks Secured", size=14)
# Setting the title for the graph
plt.title("This is an annotated barplot")
# Finally showing the plot
plt.show()
输出:
以下是基于上述方法的完整程序:
蟒蛇3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Name": ["Alex", "Bob", "Clarein", "Dexter"],
"Marks": [45, 23, 78, 65]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Name', 'Marks'])
# Defining the plot size
plt.figure(figsize=(8, 8))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Name", y="Marks", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
# x-coordinate: bar.get_x() + bar.get_width() / 2
# y-coordinate: bar.get_height()
# free space to be left to make graph pleasing: (0, 8)
# ha and va stand for the horizontal and vertical alignment
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 8),
textcoords='offset points')
# Setting the label for x-axis
plt.xlabel("Students", size=14)
# Setting the label for y-axis
plt.ylabel("Marks Secured", size=14)
# Setting the title for the graph
plt.title("This is an annotated barplot")
# Finally showing the plot
plt.show()
输出:
下面是一些使用matplotlib 库描述条形图中注释条的示例:
示例 1:
蟒蛇3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Language": ["Python", "C++", "Java"],
"Students": [75, 50, 25]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Language', 'Students'])
# Defining the plot size
plt.figure(figsize=(5, 5))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Language", y="Students", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 5),
textcoords='offset points')
# Setting the title for the graph
plt.title("Example 1")
# Finally showing the plot
plt.show()
输出:
示例 2:
蟒蛇3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Section": ["A", "B", "C", 'D', 'E'],
"Students": [0, 10, 20, 30, 40]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Section', 'Students'])
# Defining the plot size
plt.figure(figsize=(5, 5))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Section", y="Students", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 5),
textcoords='offset points')
# Setting the title for the graph
plt.title("Example 2")
# Finally showing the plot
plt.show()
蟒蛇3
# Importing libraries for dataframe creation
# and graph plotting
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Creating our own dataframe
data = {"Section": ["A", "B", "C", 'D', 'E'],
"Students": [0, 10, 20, 30, 40]}
# Now convert this dictionary type data into a pandas dataframe
# specifying what are the column names
df = pd.DataFrame(data, columns=['Section', 'Students'])
# Defining the plot size
plt.figure(figsize=(5, 5))
# Defining the values for x-axis, y-axis
# and from which dataframe the values are to be picked
plots = sns.barplot(x="Section", y="Students", data=df)
# Iterrating over the bars one-by-one
for bar in plots.patches:
# Using Matplotlib's annotate function and
# passing the coordinates where the annotation shall be done
plots.annotate(format(bar.get_height(), '.2f'),
(bar.get_x() + bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 5),
textcoords='offset points')
# Setting the title for the graph
plt.title("Example 2")
# Finally showing the plot
plt.show()
输出: