Now, we know a bunch about how you may
encode information into your visualization and how to make an
effective visualization, but we still haven't yet discussed how you
can make graphics like this, short of drawing them with
pen and paper. There are a number of packages
for plotting in Python. One of the most popular is
Matplotlib. For this course, however, I'd like to go over
plotting using a Python library called ggplot, which very closely
recreates the syntax used in R's ggplot2 library.
If Matplotlib is so widely used, why should we
use ggplot? Well, I'd like to use this package
for a few reasons. First, what it produces is
a bit more aesthetically pleasing than Matplotlib. Second, it's
an implementation of a pretty neat concept called the
grammar of graphics, which basically claims that there's a
grammar involved in composing graphical components of statistical graphics.
The gg in ggplot actually comes from
grammar of graphics. It also plays nicely with
the pandas DataFrames we've been using in
this course. To quickly summarize the ideas behind
the grammar of graphics, plots convey information
through their aesthetics such as x-position or y-position.
The elements in a given plot are
geometric shapes, such as points, lines, or bars.
Some of these shapes can have aesthetics of
their own, such as their size or their
color. You can think of creating plots in
ggplot through the grammar of graphics as adding layers
to our plot. The first step in creating
a graphic is always to create our plot, which
is essentially going to be our canvas. This
can be done by calling ggplot data aes(xvar, yvar).
Data here is going to be a pandas DataFrame, and xvar and yvar are going to be
columns in that data frame. So what we're doing
here is saying let's make a ggplot. The data
source is going to be our data frame,
and the quantities that we're interested in plotting are
xvar and yvar. This might be district and number
of Aadhaar enrollments or position and number of players,
something like that. So what we've done here is
we've made our ggplot. We've said that the data source
that it will use is pandas DataFrame, and that the
variables that we'll look at are xvar and yvar. This
might be district and number of Aadhaar enrolled if were
using our Aadhaar data or team and total number of
players if we were using our baseball data, something like
that. Okay, so, so far that we've said that we'll
have a plot which is mapping xvar to the
x-axis, yvar to the y-axis, but we haven't said yet
what type of geometric object is going to represent
this data. So if we add plus geom point to
this statement, we'll create a scatter plot. If we
also add plus geom line to the graphic, we'll connect
all these points to each other with lines. Now, say
that we wanted these points to have a particular color.
We can pass color equals coral into geom point,
and also pass color equals coral into geom line.
And after we do that, both the points and
the lines will have the color coral. This is the
second step of making a plot in ggplot, that
is choosing which type geometric objects will represent the data.
The final step here is going to be adding
some labels so that our plot will have some context,
like a title or an x-label or a y-label. This can be done much in the same way
that we added the points and lines to our
plot. We can add a ggtitle to title our
plot. An xlab, which will be x-label, to provide
an x-label. And a ylab to do the same
with the y-axis. Now all I have to do
is precede this entire command by Print. And I'll produce
a plot in Python. Why don't you try implementing
these ideas to create a graphic of your own?
أصبحت الآن تعرف قدرًا جيدًا عن
كيفية ترميز المعلومات في التصور المرئي وكيفية إنشاء تصور مرئي فعال
،ولكننا لم نتناول بعد طريقة عمل رسومات مثل هذه
لأننا لم نتمكن من تصميمها
بالورقة والقلم. هناك عدد من حزم
التخطيط البياني في Python. وتعد Matplotlib
واحدة من أشهر تلك الحزم. ومع ذلك، في هذه الدورة التدريبية، أود أن أتطرق إلى
التخطيط البياني باستخدام مكتبة Python المسماة ggplot، التي
.تعيد إنشاء الصيغة المستخدمة في مكتبة ggplot2 الخاصة بـ R على نحو جيد
إذا كان Matplotlib يستخدم على نطاق واسع جدًا، فما السبب الذي يكمن وراء
استخدامنا ggplot؟ حسنًا، أرغب في استخدام هذه الحزمة
لعدة أسباب. أولاً، ما تقدمه هذه الحزمة أفضل قليلاً
من الناحية الجمالية عما تقدمه Matplotlib. ثانيًا، إنها تعد
تنفيذًا لمفهومٍ منمقٍ جميلٍ يسمى
قواعد الرسومات، الذي يدعي أساسًا
.استخدام القواعد في تأليف مكونات رسومية للرسومات الإحصائية
وفي الواقع، تُستمد gg في ggplot
من مقابل قواعد الرسومات في الإنجليزية. كما أنها أيضا تنسجم بشكل جيد مع
pandas DataFrames التي نستخدمها
في هذه الدورة التدريبية. ولتلخيص الأفكار الكامنة وراء
قواعد الرسومات سريعًا، فإن المخططات تعرض المعلومات
.من خلال جمالياتها مثل موضع x أو موضع y
العناصر الموجودة في المخطط عبارة عن
.أشكال هندسية، مثل النقاط أو الخطوط أو الأشرطة
،تتمتع بعض هذه الأشكال بجماليات خاصة بها
مثل أحجامها أو
ألوانها. يمكنك التفكير في إنشاء مخطط في
ggplot من خلال قواعد الرسومات باعتباره إضافة طبقات
إلى المخطط. دائمًا ما تكون الخطوة الأولى في إنشاء
،الرسم هي إنشاء المخطط
الذي يمثل في الأساس سطح العمل. حيث يمكن
.تحقيق ذلك من خلال استدعاء البيانات وaes(xvar, yvar) في ggplot
تمثل البيانات هنا pandas DataFrame، ويمثل كل من xvar وyvar
أعمدة في إطار البيانات. لذا، ما سنقوم به هنا
هو إنشاء ggplot. سيكون مصدر البيانات
،هو إطار البيانات لدينا
ويكون كل من xvar وyvar
الكميات التي نرغب في تخطيطها. يمكن أن تكون منطقة وعدد من
،تسجيلات Aadhaar أو موضع وعدد اللاعبين
أو ما شابه ذلك. ما قمنا به هنا هو
أننا أنشأنا مخطط ggplot الخاص بنا. كما أننا وضحنا أن مصدر البيانات
الذي ستستخدمه هو pandas DataFrame
وأن المتغيرات التي سنضعها في الاعتبار هي xvar وyvar. يمكن أن تشمل هذه
المنطقة وعدد Aadhaar المسجل في حالة استخدامنا
بيانات Aadhaar أو يكون فريقًا وإجمالي عدد اللاعبين
،إذا كنا نستخدم بيانات البيسبول
أو ما شابه ذلك. حسنًا، ما تطرقنا إليه حتى الآن
،أنه سيكون لدينا مخطط يقوم بتخطيط xvar في المحور x
،وyvar في المحور y
ولكننا لم نتطرق حتى الآن إلى
الشكل الهندسي الذي سيمثل هذه البيانات. وإذا أضفنا نقطة geom إلى
هذه العبارة، فسننشئ رسمًا مبعثرًا. وإذا أضفنا
أيضًا سطر geom إضافيًا إلى الرسم، فسنوصِّل
كل تلك النقاط معًا باستخدام الخطوط. لنفترض، أننا نريد
.أن تأخذ هذه النقاط لونًا معينًا
،يمكننا كتابة اللون يساوي مرجاني في نقطة geom
.ونكتب كذلك اللون يساوي مرجاني في سطر geom
وبعد القيام بذلك، ستظهر
النقاط والخطوط باللون المرجاني. وتلك هي الخطوة الثانية
،في إنشاء مخطط في ggplot
.وهي اختيار نوع الشكل الهندسي الذي سيمثل البيانات
والخطوة الأخيرة هنا هي إضافة
،بعض التسميات لكي يتضمن المخطط بعضًا من السياق
مثل العنوان أو تسمية x أو تسمية y. ويمكن تنفيذ ذلك بنفس الطريقة
التي أضفنا بها النقاط والخطوط إلى
مخططنا. يمكننا إضافة ggtitle لإضافة عنوان
المخطط. وxlab التي ستكتب x-label، لتوفير
تسمية x. وستقوم ylab بالأمر ذاته
مع محور y. والآن ما يمكنني فعله هو
كتابة كلمة Print قبل هذا الأمر بالكامل. وبذلك سأنشئ
مخططًا في Python. فلم لا تجرب تنفيذ هذه الأفكار
لإنشاء رسم بياني من تصميمك؟
情報を視覚化する手法や
効果的な視覚化について学びましたが
まだ図表の作り方は説明していません
紙とペンを使わなくてもできます
Pythonに図表作成パッケージがあります
matplotlibは人気パッケージです
しかしこのコースではggplotという
Pythonライブラリを使います
Rのggplot2ライブラリと同じように使えます
matplotlibが広く使われているのに
なぜggplotを使うのでしょう
それにはいくつか理由があります
まずggplotはmatplotlibより美しい図表を作れること
またグラフィック文法という簡単で美しく
統計を図表化できる文法があるからです
ggplotのggはグラフィック文法(grammer of graphics)
から来ています
このコースで使用しているpandasとの相性もいいです
グラフイック文法を簡単に説明すると
x、yで表示項目を指定するなど
簡単に見栄えのいい図が作れます
図表の要素として使われるのは
点、線、棒などです
サイズや色などデフォルトで指定できるものもあります
レイヤー操作を身につけることで
グラフィック文法を使ってggplotで図が作成できます
最初にやることは視覚化したいデータを
入力データとして取り込むことです
ggplot(data, aes(xvar, yvar))という関数を使います
dataにはpandasのデータフレームを入力し
xvar、yvarはデータフレームの列になります
ggplotで図表を作ってみましょう
データソースには自分のデータフレームを入れ
図表で表したいものをxvarとyvarに入れます
xvarが地域でyvarがAadhaar登録者
xvarがポジションでyvarが選手数などです
まとめるとggplotで図表作成をするには
データソースにpandasのデータフレームを入れ
変数をxvarとyvarで指定するということです
Aadhaarデータならxが地域でyが登録者数
野球データならxがチームでyが選手数などです
ここまで図表の中のxvarをx軸に
yvarをy軸に設定しました
しかしデータを表現する幾何オブジェクトは
まだ指定していません
ここでgeom_pointを加えると散布図が作れます
またgeom_lineを加えれば
点と点を線で結ぶ折れ線グラフができます
色を指定したい場合は
geom_pointにピンクと入れたり
geom_lineにピンクと入れることで
点や線がピンクになります
この作業がggplotで図表をつくる第2ステップです
データを表現する
幾何オブジェクトを指定しています
最後にデータの意味を捉えやすいように
ラベルをつけます
例えばタイトルやx軸y軸の名前をつけます
これは図表に点や線を加えるのと同じ方法でできます
ggtitleのカッコ内に入れた文字がタイトルになり
xlabに入れた文字はx軸の名前に
ylabに入れた文字はy軸の名前になります
このコマンドの先頭にprintをつけて実行すると
Pythonで図表が作成されます
この方法で自分の図表を作成してみてください
Agora sabemos bastante sobre como você pode
codificar informações em sua visualização e como criar uma
visualização efetiva, mas ainda não discutimos como você
pode fazer gráficos como este, como se estivesse desenhando com
papel e caneta. Existem vários pacotes
de plotagem no Python. Um dos mais populares é o
Matplotlib. Neste curso, entretanto, quero analisar a
plotagem usando uma biblioteca Python chamada ggplot, que recria
de modo muito próximo a sintaxe usada na biblioteca ggplot2 de R.
Se Matplotlib é tão amplamente usado, por que devemos
usar o ggplot? Bem, eu gostaria de usar esse pacote
por alguns motivos. Primeiro, o que ele produz é
um pouco mais agradável esteticamente do que o Matplotlib. Em segundo lugar, é
uma implementação de um conceito muito interessante chamado
gramática dos gráficos que, basicamente, afirma que há uma
gramática envolvida na composição de componentes gráficos de gráficos estatísticos.
O gg em ggplot, na verdade, é proveniente de
gramática de gráficos. Ele também funciona bem com
as estruturas de dados do Pandas que temos usado
neste curso. Para resumir rapidamente as ideias por trás
da gramática dos gráficos, os gráficos transmitem informações
por meio de sua aparência, como a posição x ou a posição y.
Os elementos em um determinado gráfico são
formas geométricas, como pontos, linhas ou barras.
Algumas dessas formas podem ter uma aparência
própria, como tamanho
ou cor. Você pode pensar na criação de gráficos no
ggplot por meio da gramática de gráficos como a adição de camadas
em nosso gráfico. A primeira etapa na criação
de um gráfico é sempre criar a plotagem que,
essencialmente, será nossa tela. Isso
pode ser feito chamando ggplot(data, aes(xvar, yvar)).
Aqui, data será uma estrutura de dados do Pandas e xvar e yvar serão
colunas nessa estrutura de dados. Portanto, o que estamos
dizendo aqui é vamos criar um ggplot. A fonte de
dados será nossa estrutura de dados e
as quantidades que estamos interessados em representar serão
xvar e yvar. Isso pode ser um distrito e um número
de inscrições no Aadhaar ou a posição e o número de jogadores,
algo desse tipo. Então, o que fizemos aqui
foi criar nosso ggplot. Disse que a fonte de dados que
usaremos será uma estrutura de dados do Pandas
e que as variáveis que analisaremos serão xvar e yvar. Isso
pode ser um distrito e um número de inscrições no Aadhaar se
estivermos usando nossos dados Aadhaar ou
a equipe e o número total de jogadores, se estivermos usando nossos dados de beisebol,
algo desse tipo. Muito bem. Dito isso, teremos um
gráfico mapeando xvar no eixo x e
yvar no eixo y, mas não dissemos ainda qual
tipo de objeto geométrico representará
esses dados. Portanto, se incluirmos mais geom_point a
esta instrução, criaremos um gráfico de dispersão. Se também
incluirmos mais geom_line ao gráfico, conectaremos
todos esses pontos entre si com linhas. Agora, digamos
que queremos que esses pontos tenham uma cor específica.
Podemos usar color igual a coral em geom_point
e também usar color igual a coral em geom_line.
Depois de fazermos isso, os pontos e
as linhas terão a cor coral. Essa é a
segunda etapa da criação de um gráfico no ggplot,
em que escolhemos os tipos de objetos geométricos que representarão os dados.
A última etapa aqui será adicionar
alguns rótulos para que nosso gráfico tenha algum contexto,
como um título ou um rótulo de x ou um rótulo de y. Isso pode ser feito de forma muito parecida
com a que usamos para adicionar os pontos e as linhas
ao gráfico. Podemos adicionar ggtitle para dar
um título ao gráfico. E um xlab, que será x-label, para fornecer
um rótulo de x. E um ylab para fazer o mesmo
com o eixo y. Agora, tudo o que temos de fazer
é colocar Print antes de todo esse comando. E criaremos
um gráfico no Python. Por que não tenta implementar
essas ideias para criar um gráfico por conta própria?
现在,我们已经知道得太多了,比如,怎样去
将信息进行可视化,以及去达到
有效可视化程度。但目前为止,我们还没有讨论过,你该如何去
真正地把你的想法画出来,(用手上的工具)把它们画出来
通过笔和纸。已经有很多用于制图的python程序包,最有名的是Matplotlib
通过笔和纸。已经有很多用于制图的python程序包,最有名的是Matplotlib
不过在本课中,我要介绍另一种python绘图的标准库,ggplot,
Matplotlib. For this course, however, I'd like to go over
不过在本课中,我要介绍另一种python绘图的标准库,ggplot,
它沿用了R语言的ggplot2 的语法。
既然 Matplotlib 得到了广泛的应用,为什么我们却
使用这个ggplot呢,好吧,为什么用它,
我给出理由。1,它的绘制效果
比起 Matplotlib 要更美观一些。二,
它体现了一种非常有趣的概念,
叫做图形的语法,简单来说,这个概念就是指
grammar of graphics, which basically claims that there's a
在语法中要能体现统计图的各个图形组成成分。
ggplot 中的gg 实际上就是图形的语法。不仅如何,它还能很好地配合
ggplot 中的gg 实际上就是图形的语法。不仅如何,它还能很好地配合
pandas 的DataFrames 的使用,这个 DataFrame 之前我们有使用过了,
现在,我简要地阐述下图形语法内部的思想。图表可以表达一定信息,
现在,我简要地阐述下图形语法内部的思想。图表可以表达一定信息,
利用的是它们美学设计,比如两个坐标系。
图表里的元素都是几何图形,比如点线面。
图表里的元素都是几何图形,比如点线面。
一些图形有自己的美学属性,
比如大小,或是颜色。
对于用ggplot 照着图形语法进行绘图,你可以把它看作是向图表上添加图层。
对于用ggplot 照着图形语法进行绘图,你可以把它看作是向图表上添加图层。
绘图第一步,无疑,是先准备整个基本图表(的框)。
绘图第一步,无疑,是先准备整个基本图表(的框)。
它将作为我们使用的画布。
调用方式ggplot(data, aes(xvar, yvar))
这里的data(变量)是一个DataFrame的数据类型,xvar和yvar则是
这个dataframe里的两列。所以,我们在这里调用了ggplot, 数据的
这个dataframe里的两列。所以,我们在这里调用了ggplot, 数据的
来源就是这个data变量(dataframe类型)
要绘制(的对象)的数量则是由
xvar yvar控制。比如,Aadhaar中的区域和注册用户人数,
又或是球队与运动员的数目,
这类的数据。所以,来看看我们已经做了什么,
好,已经调用了ggplot, 刚刚有说过,数据源(data变量)
使用的是pandas的dataframe数据类型,我们并不使用到data里的全部数据,
目前,我们只使用xvar 和 yvar 这两列。
假设一列是地区名,另一列是Aadhaar登记人数,这些数据都在
我们的Aadhaar 数据里面; 也可以假设为球队和总的球员人数,
这些数据则是我们的棒球集里;反正数据就是这样的。
好啦,我已经废话很多了,
现在已经得到了一张图表,把xvar映射到了x轴上,
yvar映射到y轴上了,但我们还没有
确认使用哪种几何图形来表示数据。
那么,如果我们这样写,+geom_point 写到后面,
就得到一张散点图。 如果我们
再来加一句 +geom_line, 好,
每两点之间就会用直线连起来。接下来,
我们给这些点着上特别的颜色。
传参数 color="coral" 给 geom_point,
同样也把参数 color="coral" 传给 geom_line,
做完这些之后,点和线都的颜色都变coral 了,珊瑚色。
做完这些之后,点和线都的颜色都变coral 了,珊瑚色。
OK,我们用ggplot来绘图的第二步就告一段落了,
主要是去为数据选择几何图形。
最后一步,则是添加标记,这样图表才有文字说明,
最后一步,则是添加标记,这样图表才有文字说明,
比如一个标题,x轴,y轴。这个和添加点线的方法很是相近,
比如一个标题,x轴,y轴。这个和添加点线的方法很是相近,
+ggtitle('title'), +xlab('x-label')
会显示x-label,+ylab('y-label'),会显示y-label,
会显示x-label,+ylab('y-label'),会显示y-label,
会显示x-label,+ylab('y-label'),会显示y-label,现在再用
an x-label. And a ylab to do the same。
用print来处理整个命令。然后,我就得到了
一个python绘制出来的图表了。如何, 你是不是想亲手一试呢?
一个python绘制出来的图表了。如何, 你是不是想亲手一试呢?