python绘制非常漂亮的图表,python制作图表放入excel

本文详细介绍了使用Python进行图表制作,包括条形图、水平条形图、堆垛条形图、散点图、折线图、面积图、刻面、饼图、甜甜圈图、棒棒糖图以及2D马赛克和树形图的实例,展示了如何通过matplotlib和seaborn等库实现各种类型的可视化效果。
摘要由CSDN通过智能技术生成

大家好,小编来为大家解答以下问题,python制作图表和Excel制作图表,基于python的图表生成系统,今天让我们一起来看看吧!

40张python图表

1. 条形图

# 库
import numpy as np
import matplotlib.pyplot as plt
 
# 创建数据集
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))
 
# 创建条形图
plt.bar(x_pos, height)
 
# 在x轴上创建名称
plt.xticks(x_pos, bars)
 
# 显示图形
plt.show()

在这里插入图片描述

#水平条形图
import matplotlib.pyplot as plt
import numpy as np

height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
#height后面加上代码color=(0.2, 0.4, 0.6, 0.6)可以改变颜色
plt.barh(y_pos, height)

plt.yticks(y_pos, bars)
plt.show()

在这里插入图片描述

# 堆垛条形图
# 库
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import pandas as pd
rc('font', weight='bold')
bars1 = [12, 28, 1, 8, 22]
bars2 = [28, 7, 16, 4, 10]
bars3 = [25, 3, 23, 25, 17]
bars = np.add(bars1, bars2).tolist()
r = [0,1,2,3,4]
names = ['A','B','C','D','E']
barWidth = 1
plt.bar(r, bars1, color='#7f6d5f', edgecolor='white', width=barWidth)
plt.bar(r, bars2, bottom=bars1, color='#557f2d', edgecolor='white', width=barWidth)
plt.bar(r, bars3, bottom=bars, color='#2d7f5e', edgecolor='white', width=barWidth)
plt.xticks(r, names, fontweight='bold')
plt.xlabel("group")
plt.show()

在这里插入图片描述

2.散点图

import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(1234)

# Generate data
x = rng.lognormal(size=200)
y = x + rng.normal(scale=5 * (x / np.max(x)), size=200)

# Initialize layout
fig, ax = plt.subplots(figsize = (9, 6))

# Add scatterplot
ax.scatter(x, y, s=60, alpha=0.7, edgecolors="k");
![在这里插入图片描述](https://img-blog.csdnimg.cn/a57af7e41bf94b0fb6b62b27d8a5dbbb.png)

3.折线图

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

在这里插入图片描述

在这里插入图片描述

4.面积图和刻面

# libraries
import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
 
# Create a dataset
my_count=["France","Australia","Japan","USA","Germany","Congo","China","England","Spain","Greece","Marocco","South Africa","Indonesia","Peru","Chili","Brazil"]
df = pd.DataFrame({
   
"country":np.repeat(my_count, 10),
"years":list(range(2000, 2010)) * 16,
"value":np.random.rand(160)
})
 
# Create a grid : initialize it
g = sns.FacetGrid(df, col='country', hue='country', col_wrap=4, )

# Add the line over the area with the plot function
g = g.map(plt.plot, 'years', 'value')
 
# Fill the area with fill_between
g = g.map(plt.fill_between, 'years', 'value', alpha=0.2).set_titles("{col_name} country")
 
# Control the title of each facet
g = g.set_titles("{col_name}")
 
# Add a title for the whole plot
plt.subplots_adjust(top=0.92)
g = g.fig.suptitle('Evolution of the value of stuff in 16 countries')

# Show the graph
plt.show()

在这里插入图片描述

5.散点图

# 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-RyQuAWhB-1685956274523)(output_12_0.png)]

6. 基本饼图

# 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-qbtqrHEZ-1685956274524)(output_14_0.png)]

6.基本甜甜圈图

# 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-EMUEG6Wq-1685956274524)(output_16_0.png)]

7.棒棒糖图

# libraries
import matplotlib.pyplot as plt
import numpy as np
 
# create data
x=range(1,41)
values=np.random.uniform(size=40)
 
# stem function
plt.stem(x, values)
plt.ylim(0, 1.2)
plt.show()
 
# stem function: If x is not provided, a sequence of numbers is created by python:
plt.stem(values)
plt.show()

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

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

8. 2D马赛克

# libraries
import matplotlib.pyplot as plt
import numpy as np

# Data
x = np.random.normal(size=50000)
y = x * 3 + np.random.normal(size=50000)

# A histogram 2D
plt.hist2d(x, y, bins=(50, 50), cmap=plt.cm.Reds)

# Add a basic title
plt.title("A 2D histogram")

# Show the graph
plt.show()

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

9.树形图

# libraries
import pandas as pd
import matplotlib.pyplot as plt
import squarify    # pip install squarify (algorithm for treemap)
 
# If you have 2 lists
squarify.plot(sizes=[13,22,35,5], label=["group A", "group B", "group C", "group D"], alpha=.7 )
plt.axis('off')
plt.show()
 
# If you have a data frame
df = pd.DataFrame({
   'nb_people':[8,3,4,2], 'group':["group A", "group B", "group C", "group D"] })
squarify.plot(sizes=df['nb_people'], label=df['group'], alpha=.8 )
plt.axis('off')
plt.show() 

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

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

10.带有颜色映射值的树状图

#libraries
import matplotlib
import matplotlib.pyplot as plt
import squarify # pip install squarify (algorithm for treemap)</pre>
 
# Create a dataset:
my_values=[i**3 for i in range(1,100)]
 
# create a color palette, mapped to these values
cmap = matplotlib.cm.Blues
mini=min(my_values)
maxi=max(my_values)
norm = matplotlib.colors.Normalize(vmin=mini, vmax=maxi)
colors = [cmap(norm(value)) for value in my_values]
 
# Change color
squarify.plot(sizes=my_values, alpha=.8, color=colors 
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Python绘制Excel中的图表,你可以使用pandas和matplotlib这两个库。首先,你需要导需要使用的模块,如pandas和matplotlib.pyplot。然后,使用pandas的read_excel函数读取Excel文件,并将数据存储在一个变量中,比如people。接下来,你可以使用matplotlib.pyplot的plot函数创建图表,指定x轴和y轴的数据。最后,使用plt.show()函数显示图表。 以下是一个示例代码: ```python import pandas as pd import matplotlib.pyplot as plt from matplotlib import rcParams rcParams\['font.family'\] = 'simhei' # 读取目标表格文件,并用people代表读取到的表格数据 people = pd.read_excel('test.xlsx') # 在控制台中输出表格数据 print(people) # x轴是姓名,y轴是年龄 people.plot.bar(x='姓名', y='年龄') plt.show() ``` 这段代码会读取名为test.xlsx的Excel文件,并将姓名列作为x轴,年龄列作为y轴,然后绘制柱状图并显示出来。你可以根据自己的需求修改代码中的文件名和列名。 希望对你有帮助! #### 引用[.reference_title] - *1* *3* [Python读取excel表格数据并绘制成柱状图 | 数据排序、柱状图颜色、标签乱码等问题通通能够解决!](https://blog.csdn.net/python03011/article/details/131102325)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python(十七)- Excel操作:xlsxwriter绘制图表](https://blog.csdn.net/weixin_41599858/article/details/115278504)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值