pyecharts柱状图
这里使用 pyecharts 1.x
版本
简单绘制
先简单绘制一个柱状图开开眼界
from pyecharts.charts import Bar
x = ['aaa','bbb','ccc','ddd','eee'] # x轴数据
y1 = [10, 20, 30, 40, 50]
y2 = [20, 10, 50, 15, 38]
bar = Bar()
bar.add_xaxis(x) #添加x轴
bar.add_yaxis('y1', yaxis_data= y1) #添加y轴
bar.add_yaxis('y2', yaxis_data= y2) #添加y轴
bar.render_notebook() #在jupyter中显示
注意x, y 轴数据都是列表形式,不能用array数组
主题设置
pyecharts还提供了其他风格的主题,需要先导入主题模块:
from pyecharts.globals import ThemeType
然后在创建 Bar()
实例时添加参数 {'theme':ThemeType.主题}
即可
如下:
bar = Bar({'theme':ThemeType.主题})
以下是pyecharts提供的一些主题:
BUILTIN_THEMES = ["light", "dark", "white"]
LIGHT = "light"
DARK = "dark"
WHITE = "white"
CHALK: str = "chalk"
ESSOS: str = "essos"
INFOGRAPHIC: str = "infographic"
MACARONS: str = "macarons"
PURPLE_PASSION: str = "purple-passion"
ROMA: str = "roma"
ROMANTIC: str = "romantic"
SHINE: str = "shine"
VINTAGE: str = "vintage"
WALDEN: str = "walden"
WESTEROS: str = "westeros"
WONDERLAND: str = "wonderland"
使用方法例如下:
bar = Bar({'theme':ThemeType.LIGHT})
bar = Bar({'theme':ThemeType.DARK})
其他可以自己试一下
Faker模块
Faker含有一些数据,学习的时候可以直接拿来用,用法:
- 导入 Faker 模块
from pyecharts.faker import Faker
- 添加 横轴数据,之后会随机抽取一组数据出来
x = Faker.choose()
看一下横轴都可以取哪些数据
def choose(self) -> list: #表示数据是列表
return random.choice(
[
self.clothes,
self.drinks,
self.phones,
self.fruits,
self.animal,
self.dogs,
self.week,
]
)
这是 Faker 类的一个方法,有这几种类型的标签clothes
,drinks
,phones
,fruits
,animal
,dogs
,week
,
数据的具体内容如下:
clothes = ["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]
drinks = ["可乐", "雪碧", "橙汁", "绿茶", "奶茶", "百威", "青岛"]
phones = ["小米", "三星", "华为", "苹果", "魅族", "VIVO", "OPPO"]
fruits = ["草莓", "芒果", "葡萄", "雪梨", "西瓜", "柠檬", "车厘子"]
animal = ["河马", "蟒蛇", "老虎", "大象", "兔子", "熊猫", "狮子"]
cars = ["宝马", "法拉利", "奔驰", "奥迪", "大众", "丰田", "特斯拉"]
dogs = ["哈士奇", "萨摩耶", "泰迪", "金毛", "牧羊犬", "吉娃娃", "柯基"]
week = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
- 添加纵轴数据,纵轴数据也是随机产生的,
y = Faker.values()
看下源码:
def values(start: int = 20, end: int = 150) -> list:
return [random.randint(start, end) for _ in range(7)]
可见,会产生一个含有7个元素的列表,数据大小位于20到150之间。
现在利用 这些随机产生的数据绘制一个柱状图:
from pyecharts.charts import Bar
from pyecharts.faker import Faker
from pyecharts.globals import ThemeType
bar = (
Bar({"theme": ThemeType.MACARONS}) #主题设置
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values())
.add_yaxis("商家B", Faker.values())
)
bar.render_notebook()
注意每次运行的结果都是不一样的,因为横轴、纵轴数据每次都是随机的。