1.matplotlib scatter绘制散点图时颜色设置参数c
在matplotlib中,可以通过设置scatter函数的参数'c'来指定散点图的颜色。
设置散点图颜色:
- 使用单一颜色:可以将参数'c'设置为一个颜色名称字符串,如'red'、'blue'等。
import matplotlib.pyplot as plt
x = 1
y = 1
plt.scatter(x, y, c='red')
plt.show()
- 使用RGB颜色:可以将参数'c'设置为一个3元素的RGB颜色向量,其中每个元素的值范围为0到1。
import matplotlib.pyplot as plt
x = 1
y = 1
plt.scatter(x, y, c=(0.5, 0.2, 0.8))
plt.show()
- 使用自定义颜色映射(colormap):可以将参数'c'设置为一个与数据点数量相同的向量,然后使用colormap函数来定义颜色映射。
颜色映射是一系列颜色,它们从起始颜色渐变到结束颜色。在可视化中,颜色映射用于突出数据的规律。
模块pyplot内置了一组颜色映射。
import matplotlib.pyplot as plt
x_values = list(range(1, 1001)) #包含数字1—1000
y_values = [x**2 for x in x_values] #计算平方值
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=40)
#颜色映射——颜色渐#变。我们将参数c设置成一个y值列表,并使用参数cmap告诉pyplot使用哪个颜色的映射。##这些代码将y值较小##的点显示为浅蓝色,并将y值较大的点设置为深蓝色。
plt.show()
以上代码演示了如何使用单一颜色、RGB颜色和自定义颜色映射来设置scatter函数的颜色。根据具体需求选择适合的方法。
2.matplotlib画图隐藏坐标失败
在练习matplotlib的scatter的随机漫步图过程中,有一个设置隐藏坐标轴的方法代码如下:
#隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
执行后,坐标轴仍没有隐藏,甚至在pycharm中连随机漫步图都绘制不出来了:
1,隐藏坐标轴方法设置需要在scatter之前配置,否则无效,即隐藏坐标轴需要提前配置
plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolor='none',s=15) 之前,添加隐藏坐标轴的代码。
2,plt.axes()方法使用时,必须将它赋值给一个变量,然后调用它才可以正常使用
current_axes = plt.axes()
current_axes.get_xaxis().set_visible(False)
current_axes.get_yaxis().set_visible(False)
经过以上处理,坐标轴隐藏设置成功生效
示例:
point_numbers = list(range(rw.num_points)) #range()生成一个数字列表,其中包含的数字个 数与漫步包含的点数相同
# 隐藏坐标轴.使用函数plt.axes()修改坐标轴,来将每条坐标轴的可见性都设置为False
current_axes = plt.axes()
current_axes.get_xaxis().set_visible(False)
current_axes.get_yaxis().set_visible(False)
#为根据漫步中各点的先后顺序进行着色,我们传递参数c,并将其设置为一个列表,其中包含各点的先后顺序。由于这些点是按顺序绘制的,因此给参数c指定的列表只需要包含数字1~5000
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, s=5)
#突出起点和终点
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none',s=100)
【参考】:链接:https://blog.csdn.net/m0_46478042/article/details/139710655
3. pygal绘制图表字体大小设置没起作用
- 问题代码:
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
以上设置了图表标题、副标签和主标签的字体大小。
在图表中,副标签是 x 轴上的项目名以及 y 轴上的大部分数字。主标签是 y 轴上为5000整数倍的刻度;这些标签应更大,以与副标签区分开来。
- 修改代码:
--snip-- my_style = LS('#333366', base_style=LCS) my_style.title_font_size = 24 my_style.label_font_size = 14 my_style.major_label_font_size = 16 #改进图表样式 my_config = pygal.Config()
...
chart = pygal.Bar(my_config, style=my_style)
--snip--
(这只是其中一个修改方法,更多的可参考下文)
《Python编程:从入门到实践》17.2.1节中绘制条形图“GitHub上受欢迎程度最高的Python项目”,书中源代码如下:
#coding=gbk
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
# 探索有关仓库的信息
repo_dicts = response_dict['items']
#print("Repositories returned:", len(repo_dicts))
names, stars = [], []
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
# 可视化
my_style = LS('#333366', base_style=LCS)
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
#以下三句设置字体的语句有问题
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15 # 将标签截断为15个字符
# 如果将鼠标指向被截断的标签,将显示完整标签
my_config.show_y_guides = False # 隐藏图表中的水平线(y guide lines)
my_config.width = 1000 # 图标宽度,默认800
chart = pygal.Bar(my_config, style=my_style)
#chart.config.style.title_font_size = 24
chart.title = 'Most-Starred Python Projects on GitHub'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('python_repos.svg')
查阅pygal文档,想看看官方对label_font_size和major_label_font_size的解释。
pygal.config module — pygal 2.0.0 documentation
pygal.style module — pygal 2.0.0 documentation
首先查看config类
class pygal.config.Config(**kwargs)
却发现其中并没有title_font_size、label_font_size、major_label_font_size这几个属性。
再检索title_font_size,发现这个属性出现在style类中,于是查看style类
class pygal.style.Style(**kwargs)
发现其包含有title_font_size、label_font_size、major_label_font_size三个属性。而config类中包含一个名为style的style类属性。
class Style(object):
"""Styling class containing colors for the css generation"""
plot_background = 'rgba(255, 255, 255, 1)'
background = 'rgba(249, 249, 249, 1)'
value_background = 'rgba(229, 229, 229, 1)'
foreground = 'rgba(0, 0, 0, .87)'
foreground_strong = 'rgba(0, 0, 0, 1)'
foreground_subtle = 'rgba(0, 0, 0, .54)'
# Monospaced font is highly encouraged
font_family = ('Consolas, "Liberation Mono", Menlo, Courier, monospace')
label_font_family = None
major_label_font_family = None
value_font_family = None
value_label_font_family = None
tooltip_font_family = None
title_font_family = None
legend_font_family = None
no_data_font_family = None
label_font_size = 10
major_label_font_size = 10
value_font_size = 16
value_label_font_size = 10
tooltip_font_size = 14
title_font_size = 16
legend_font_size = 14
no_data_font_size = 64
...
注释掉my_config.title_font_size = 24,绘制出来的图标也是一样的,说明那这句代码没有起作用。
因为config类中包含属性style,尝试将my_config.title_font_size = 24改为my_config.style.title_font_size = 24,绘制出的柱状图标题字体大小未发生改变,逐语句调试发现title_font_size默认值为16。
将my_config.title_font_size = 24注释掉,在chart = pygal.Bar(my_config, style=my_style)后面添加一行代码chart.config.style.title_font_size = 24,成功改变了标题字体大小。
可是my_config.style.title_font_size = 24明明修改了config类实例my_config中的属性style中的属性title_font_size,为什么在建立一个Bar实例chart时chart = pygal.Bar(my_config, style=my_style),没能将这个参数传递给柱状图呢?
通过逐语句调试发现,在建立一个Bar实例时,先会进行BaseGraph类的初始化(代码如下),首先传递config参数,然后传递余下的关键词参数。
class BaseGraph(object):
"""Chart internal behaviour related functions"""
_adapters = []
def __init__(self, config=None, **kwargs):
"""Config preparation and various initialization"""
if config:
if isinstance(config, type):
config = config()
else:
config = config.copy()
else:
config = Config()
config(**kwargs)
self.config = config
self.state = None
self.uuid = str(uuid4())
self.raw_series = []
self.xml_filters = []
my_config确实传递给了BaseGraph类的config,包括my_config的style属性也传递给了config的style属性,此时title_font_size为24,问题发生在发生在**kwargs的传递,**kwargs传递完成后,title_font_size变为默认值16。**kwargs只收集了一个关键词为style的实参my_style。而在上述代码中可以看到,**kwargs收集的关键词参数,都传递给了BaseGraph类的config。
这时我才意识到,my_style其实是一个style类,其中也包含属性title_font_size,在创建my_style时,只是传递了位置实参color,和关键词实参base_style,并没有修改其中的title_font_size,所以my_style的属性title_font_size为默认值16,在创建Bar实例时,通过关键词实参传递给了chart。明白了这其中的参数传递过程后,就知道应该怎样有效地修改title_font_size了。
除了上面提及的一种方法外,还可以直接修改my_style中的title_font_size:
my_style.title_font_size = 24
或者在创建style实例my_style时,就通过关键词实参传递title_font_size的值:
my_style = LS('#333366', base_style=LCS, title_font_size=24)
既然config实例my_config中包含属性style,也可以修改my_config中的style属性,省去style实例my_style的创建和传递:
my_config.style.title_font_size = 24
my_config.style = LS('#333366', base_style=LCS)
chart = pygal.Bar(my_config)
- 根本原因: pygal 2.0.0发生过如下变动: