В этом документе описывается, как создавать круговые диаграммы с помощью API диаграмм.
Оглавление
Особенности диаграммы
| Стандартные функции
|
Обзор
Круговые диаграммы хороши для отображения простой пропорциональной информации от части к целому. Вы можете создать круговую диаграмму с одной серией, где каждая серия состоит из нескольких срезов, или концентрические диаграммы с несколькими сериями.
Каждая серия описывает одну круговую диаграмму, а каждое значение данных указывает один срез. При использовании вложенных круговых диаграмм (описанных ниже) используйте несколько рядов.
Чтобы отобразить текст, связанный с фрагментом, вам придется использовать либо метки круговой диаграммы , либо легенду диаграммы . Метки круговой диаграммы представляют собой текст вокруг диаграммы с линиями, направленными к срезу. Легенды — это текст, связанный цветом.
Этикетки | Легенда | Этикетки и легенда |
---|---|---|
chl=January|February|March|April | chdl=January|February|March|April | chl=January|February|March|April |
Значения отображаются относительно друг друга: поэтому диаграмма со значениями 1,2,3 будет выглядеть так же, как диаграмма со значениями 100,200,300. Однако при использовании данных текстового формата значения больше 100 обрезаются до 100, поэтому вам нужно будет использовать текстовый формат с пользовательским масштабированием для правильного отображения фрагментов больше 100 (используйте параметр chds
с минимальными/максимальными значениями chds=0,< max-slice-size >
).
Отрицательные значения отображаются как пустые фрагменты соответствующего размера.
Типы диаграмм
Существует три основных типа круговых диаграмм, которые вы можете создать: плоские, концентрические и трехмерные. Укажите круговую диаграмму со следующим синтаксисом:
Синтаксис
cht=<chart_type>
Где < chart_type >
— один из следующих типов:
Параметр | Описание | Пример |
---|---|---|
| Двумерная круговая диаграмма. Предоставляйте только один ряд данных; последующие серии данных игнорируются. По умолчанию цвета сегментов диаграммы интерполируются от темно-оранжевого до бледно-желтого. Укажите другие цвета, как описано в разделе «Цвета серии» . Укажите метки с помощью API Google Chart вычисляет радиус круга по минимальному значению ширины и высоты, указанному в параметре размера диаграммы ( | |
| Трехмерная круговая диаграмма. Укажите данные и форматирование так же, как для двумерных круговых диаграмм выше. Если вы включаете метки в трехмерную круговую диаграмму, вам, вероятно, придется указать размер ширины, в 2,5 раза превышающий размер высоты, чтобы гарантировать, что ваши метки будут полностью видны. | |
| Концентрическая круговая диаграмма. Предоставьте два или более ряда данных. | |
Все типы | Отрицательные числа в данных вызывают «пустые» срезы. | cht=pc |
Серия Цвета chco
Вы можете указать цвета всех значений, каждого значения или некоторых значений, используя параметр chco
.
Синтаксис
chco=<slice_1>|<slice_2>|<slice_n>,<series_color_1>,...,<series_color_n>
- < цвет >
- Цвета срезов в шестнадцатеричном формате RRGGBB . Укажите один цвет серии, и все фрагменты в этой серии будут окрашены в градации этого цвета от самого темного (первый элемент данных) до самого светлого (последний элемент данных). Укажите два или более цветов, разделенных символом | для описания отдельных цветов срезов. Если у вас есть несколько рядов (то есть диаграмма с концентрическими кольцами), вы можете указать значения для разных рядов, разделяя значения запятой. Если задано меньше цветов срезов/серий, чем отображается срезов/серий, диаграмма будет циклически перемещаться от начала списка срезов для серии или списка серий для диаграммы. Вы не можете указать отдельный градиент для каждой серии на диаграмме с несколькими сериями.
Описание | Пример |
---|---|
Укажите один цвет, чтобы иметь градации от самого темного (первый фрагмент) до самого светлого (последний фрагмент). | |
Определение градиента; здесь от желтого к красному. |
|
Определение отдельных цветов срезов; укажите один цвет для каждого фрагмента. | chd=t:10,20,30 |
На этой диаграмме есть два ряда данных, но цвет указан как один градиент на всех срезах от желтого до красного (BBBB00–BB0000). | chco=BBBB00,BB0000 |
Вот концентрическая диаграмма, которая включает в себя как цвета серий, так и цвета отдельных срезов. Диаграмма содержит два концентрических ряда данных. В удобочитаемой форме цвета: chco=зеленый|красный,синий|желтый. Запятая разбивает это на две серии:
| chd=s:eYY,ORVM |
Ярлыки круговой диаграммы chl
Вы можете указать метки для отдельных фрагментов круговой диаграммы, используя параметр chl
. Вы также можете отображать легенду с одинаковыми или разными значениями, по одной записи легенды для каждого среза.
Примечание о строковых значениях. В строках меток разрешены только символы, безопасные для URL. В целях безопасности вам следует закодировать URL-адресом все строки, содержащие символы, не входящие в набор символов 0-9a-zA-Z
. Кодировщик URL-адресов можно найти здесь .
Синтаксис
chl= <label_value>| ... <label_value>
- <значение_метки >
- Строковое значение, применяемое к срезу. Метки последовательно применяются к точкам данных в
chd
. Если у вас есть несколько рядов (например, для концентрической круговой диаграммы), метки применяются ко всем точкам во всех последовательностях в порядке, указанном вchd
. Используйте разделитель вертикальной черты (|
) между каждой меткой. Укажите недостающее промежуточное значение, используя два последовательных символа вертикальной черты без пробела между ними:||
. Вам не нужно маркировать все срезы.
Примеры
Описание | Пример |
---|---|
Метки для трехмерной круговой диаграммы. | |
Указывая размер диаграммы с помощью Как правило, для правильного отображения меток ширина двумерной круговой диаграммы должна быть примерно в два раза больше ее высоты, а ширина трехмерной круговой диаграммы должна быть примерно в два с половиной раза шире ее высоты. В первом примере метки отображаются лишь частично, поскольку диаграмма недостаточно широка. Второй пример показывает, что для полного отображения меток диаграмме необходима ширина 280 пикселей. (Границы добавлены явно к элементу | |
Ротация круговой диаграммы chp
По умолчанию первая серия рисуется начиная с 3:00 и продолжается по часовой стрелке вокруг диаграммы, но вы можете указать собственное вращение с помощью параметра chp
.
Синтаксис
chp=<radians>
- <радианы >
- Значение с плавающей запятой, описывающее, на сколько радиан нужно повернуть диаграмму по часовой стрелке. Один полный оборот составляет 2 π (2 пи — около 6,28) радиан.
Примеры
Описание | Пример |
---|---|
Чтобы изменить ориентацию круговой диаграммы, используйте | |
Вот еще один пример вращения круговой диаграммы. Их можно комбинировать с маркерами формы диаграммы для создания интересных эффектов . |
Стандартные функции
Остальные функции на этой странице являются стандартными функциями диаграмм.
Название графика chtt
, chts
[ Все графики ]
Вы можете указать текст заголовка, цвет и размер шрифта для диаграммы.
Синтаксис
chtt=<chart_title> chts=<color>,<font_size>,<opt_alignment>
chtt
— указывает заголовок диаграммы.
- < название_диаграммы >
- Название для отображения диаграммы. Вы не можете указать, где это будет отображаться, но при желании вы можете указать размер и цвет шрифта. Используйте знак + для обозначения пробелов и символ вертикальной черты (
|
) для обозначения разрывов строк.
chts
[ Необязательно ] — цвета и размер шрифта для параметра chtt
.
- <цвет >
- Цвет заголовка в шестнадцатеричном формате RRGGBB . Цвет по умолчанию — черный.
- <размер_шрифта >
- Размер шрифта заголовка, в пунктах.
- <opt_alignment>
- [ Необязательно ] Выравнивание заголовка. Выберите одно из следующих строковых значений с учетом регистра: «l» (слева), «c» (по центру), «r» (справа). По умолчанию — «с».
Примеры
Описание | Пример |
---|---|
Диаграмма с заголовком, использующая цвет и размер шрифта по умолчанию. Укажите пробел со знаком плюс ( Используйте символ вертикальной черты ( | chtt=Site+visitors+by+month| |
Диаграмма с синим заголовком размером 20 пунктов, выровненным по правому краю. | chtt=Site+visitors |
Текст и стиль легенды диаграммы chdl
, chdlp
, chdls
[ Все диаграммы ]
Легенда — это боковая часть диаграммы, содержащая небольшое текстовое описание каждой серии. Вы можете указать текст, связанный с каждой серией в этой легенде, и указать, где на диаграмме он должен появиться.
См. также chma
, чтобы узнать, как установить поля вокруг легенды.
Примечание о строковых значениях: в строках меток разрешены только символы, безопасные для URL. В целях безопасности вам следует закодировать URL-адресом все строки, содержащие символы, не входящие в набор символов 0-9a-zA-Z
. Кодировщик URL-адресов можно найти в документации по визуализации Google .
Синтаксис
chdl=<data_series_1_label>|...|<data_series_n_label> chdlp=<opt_position>|<opt_label_order> chdls=<color>,<size>
chdl
— текст каждой серии для отображения в легенде.
- < метка_серии_данных >
- Текст для записей легенды. Каждая метка применяется к соответствующей серии в массиве
chd
. Используйте знак + для пробела. Если вы не укажете этот параметр, на диаграмме не будет легенды. Невозможно указать разрыв строки в метке. Легенда обычно расширяется, чтобы вместить текст легенды, а область диаграммы сжимается, чтобы вместить легенду.
chdlp
— [ необязательно ] Положение легенды и порядок записей легенды. Вы можете указать <position> и/или <label_order> . Если вы укажете оба, разделите их чертой. Вы можете добавить «s» к любому значению, если хотите, чтобы пустые записи легенды в chdl
были пропущены в легенде. Примеры: chdlp=bv
, chdlp=r
, chdlp=bv|r
, chdlp=bvs|r
- < опт_позиция >
- [ Необязательно ] Указывает положение легенды на диаграмме. Чтобы указать дополнительное отступы между легендой и областью диаграммы или границей изображения, используйте параметр
chma
. Выберите одно из следующих значений:-
b
– Легенда внизу диаграммы, записи легенды расположены в горизонтальном ряду. -
bv
— легенда внизу диаграммы, записи легенды в вертикальном столбце. -
t
— Легенда вверху диаграммы, записи легенды расположены в горизонтальном ряду. -
tv
— Легенда вверху диаграммы, записи легенды в вертикальном столбце. -
r
— [ по умолчанию ] Легенда справа от диаграммы, записи легенды в вертикальном столбце. -
l
— Легенда слева от диаграммы, записи легенды в вертикальном столбце.
-
- <opt_label_order>
- [ Необязательно ] Порядок отображения меток в легенде. Выберите одно из следующих значений:
-
l
[ По умолчанию для вертикальных легенд ] Отображать метки в порядке, указанном вchdl
. -
r
— отображать метки в порядке, обратном заданномуchdl
. Это полезно в составных гистограммах, чтобы показать легенду.
в том же порядке, в котором появляются полосы. -
a
— [ По умолчанию для горизонтальных легенд ] Автоматическое упорядочение: примерно означает сортировку по длине, сначала самый короткий, измеряемый в блоках по 10 пикселей. Если два элемента имеют одинаковую длину (разделены на блоки по 10 пикселей), первым будет отображаться тот, который указан первым. -
0,1,2...
— Пользовательский порядок меток. Это список индексов меток, отсчитываемых от нуля, изchdl
, разделенных запятыми.
-
chdls
— [ необязательно ] Задает цвет и размер шрифта текста легенды.
- < цвет >
- Цвет текста легенды в шестнадцатеричном формате RRGGBB .
- < размер >
- Размер пункта текста легенды.
Примеры
Описание | Пример |
---|---|
Два примера легенд. Укажите текст легенды в том же порядке, что и ряд данных. | chdl=NASDAQ|FTSE100|DOW chdl=First|Second|Third |
На первой диаграмме показаны записи горизонтальной легенды ( | |
В этом примере показано изменение размера шрифта. | |
Поля диаграммы chma
[ Все диаграммы ]
Вы можете указать размер полей диаграммы в пикселях. Поля рассчитываются внутрь от указанного размера диаграммы ( chs
); Увеличение размера поля не увеличивает общий размер диаграммы, а, при необходимости, уменьшает ее область.
Поля по умолчанию — это все, что осталось после расчета размера диаграммы. Это значение по умолчанию зависит от типа диаграммы. Указанные вами поля являются минимальным значением; если в области диаграммы остается место для полей, размер поля будет таким же, как и оставшееся; вы не можете сжимать поля меньше, чем требуется для любых легенд и надписей. Вот диаграмма, показывающая основные части диаграммы:
Поля диаграммы включают метки осей и область легенды . Размер области легенды изменяется автоматически, чтобы точно соответствовать тексту, если только вы не укажете большую ширину с помощью Совет: Если в гистограмме столбцы имеют фиксированный размер (по умолчанию), ширину области диаграммы нельзя уменьшить. Вы должны указать меньший или изменяемый размер полосы с помощью |
Синтаксис
chma= <left_margin>,<right_margin>,<top_margin>,<bottom_margin>|<opt_legend_width>,<opt_legend_height>
- < левое_поле >, < правое_поле >, < верхнее_поле >, < нижнее_поле >
- Минимальный размер поля вокруг области диаграммы в пикселях. Увеличьте это значение, чтобы включить некоторые отступы, чтобы метки осей не сталкивались с границами диаграммы.
- <opt_legend_width> , <opt_legend_height>
- [ Необязательно ] Ширина поля вокруг легенды в пикселях. Используйте это, чтобы легенда не сталкивалась с областью диаграммы или краями изображения.
Примеры
Описание | Пример |
---|---|
В этом примере диаграмма имеет минимальное поле в 30 пикселей с каждой стороны. Поскольку ширина легенды диаграммы превышает 30 пикселей, поле справа устанавливается на ширину легенды диаграммы и отличается от других полей. Метки осей находятся за пределами области графика и поэтому рисуются внутри поля. |
|
Чтобы добавить поле вокруг легенды, установите значение для параметров В этом примере ширина легенды составляет примерно 60 пикселей. Если вы установите для |
|
Стили и метки осей [ линия, полоса, Google-o-meter, радар, рассеяние ]
Вы можете указать, какие оси отображать на диаграмме, и присвоить им собственные метки и позиции, диапазоны и стили.
Не на всех диаграммах по умолчанию отображаются линии осей. Вы можете точно указать, какие оси должна отображать ваша диаграмма, используя параметр chxt
. На линиях оси по умолчанию не отображаются числа; вы должны указать ось в параметре chxt
для отображения чисел.
Вы можете выбрать, чтобы на ваших осях отображались числа, отражающие значения данных, или вы можете указать собственные оси. По умолчанию отображаются числовые значения в диапазоне от 0 до 100. Однако вы можете изменить этот диапазон с помощью chxr
для отображения любого диапазона, а также стилизовать значения (например, для отображения символов валюты или десятичных знаков) с помощью chxs
.
Если вы решите использовать пользовательские значения, например: «Пн, вторник, среда», вы можете использовать параметр chxl
. Чтобы разместить эти метки в определенных местах вдоль оси, используйте параметр chxp
.
Наконец, вы можете использовать параметры chxs
и chxtc
для указания цвета, размера, выравнивания и других свойств как пользовательских, так и числовых меток осей.
Примечание о строковых значениях: в строках меток разрешены только символы, безопасные для URL. В целях безопасности вам следует закодировать URL-адресом все строки, содержащие символы, не входящие в набор символов 0-9a-zA-Z
. Кодировщик URL-адресов можно найти в документации по визуализации Google .
В этом разделе рассматриваются следующие темы:
- Видимые оси (
chxt
) — какие оси отображать. - Диапазон оси (
chxr
) — диапазон значений для каждой оси. - Пользовательские метки осей (
chxl
) — пользовательские значения для отображения на оси. - Позиции меток по осям (
chxp
) — размещение пользовательских меток вдоль каждой оси. - Стили меток осей (
chxs
) — цвет, размер, выравнивание и форматирование меток осей. - Стили делений оси (
chxtc
) — длина делений для определенной оси.
Видимые оси chxt
Гистограммы, линейные, лепестковые и точечные диаграммы по умолчанию отображают одну или две оси, но эти линии не содержат значений. Чтобы отобразить значения на линиях осей или изменить отображаемые оси, вы должны использовать параметр chxt
. По умолчанию значения осей находятся в диапазоне от 0 до 100, если вы не масштабируете их явно с помощью свойства chxr
. Чтобы скрыть все линии осей на линейной диаграмме, укажите :nda
после значения типа диаграммы в параметре cht
(пример: cht= lc:nda
).
По умолчанию на верхней и нижней осях не отображаются деления значений, а на левой и правой осях они отображаются. Вы можете изменить это поведение, используя параметр chxs
.
Синтаксис
chxt= <axis_1> ,..., <axis_n>
- < ось >
- Ось для отображения на диаграмме. Доступные оси:
-
x
— нижняя ось X -
t
– верхняя ось X [ не поддерживается Google-o-Meter ] -
y
— левая ось Y -
r
— правая ось Y [ не поддерживается Google-o-Meter ]
-
Вы можете указать несколько осей одного типа, например: cht=x,x,y
. Это объединит два набора осей X в нижней части диаграммы. Это полезно при добавлении пользовательских меток вдоль оси, отображающей числовые значения (см. пример ниже). Оси рисуются изнутри наружу, поэтому, если у вас есть x,x
, первый x относится к самой внутренней копии, следующий x относится к следующей внешней копии и так далее.
Примеры
Описание | Пример |
---|---|
В этом примере показана линейная диаграмма с осями X, Y, верхней осью (t) и правой осью (r). Поскольку метки не указаны, по умолчанию для диаграммы используется диапазон от 0 до 100 для всех осей. Обратите внимание, что по умолчанию верхняя и нижняя оси не имеют меток рядом с метками. |
|
Вы можете включить несколько наборов меток для каждой оси, включив одно и то же значение несколько раз. В этом примере показаны два набора осей x и два набора осей y. Это не особенно полезно при использовании только меток осей по умолчанию, как показано здесь. Но вы можете указать собственные метки для каждой копии каждой оси, используя параметр chxl . | chxt=x,x,y,y chxt=x,x,y,y |
В этом примере показана горизонтальная гистограмма с осью X, осью Y, верхней осью T и правой осью R. Метки осей опущены, поэтому API диаграмм отображает диапазон от 0 до 100 для оси X и для оси T. Диапазон по оси Y и по оси R определяется количеством столбцов. В данном случае имеется пять столбцов, поэтому API диаграмм отображает диапазон от 0 до 4. Первая метка располагается по центру основания первого столбца, вторая метка — по центру основания второго столбца и т. д. . |
|
Вы можете отключить оси по умолчанию в линейной диаграмме, указав :nda после типа диаграммы. | cht=lc:nda |
Диапазон оси chxr
Вы можете указать диапазон значений, которые отображаются на каждой оси независимо, используя параметр chxr. Обратите внимание, что это не меняет масштаб элементов диаграммы, а только масштаб меток осей. Если вы хотите, чтобы номера осей описывали фактические значения данных, установите для <start_val> и <end_val> нижнее и верхнее значения диапазона вашего формата данных соответственно. См. «Масштабирование оси» для получения дополнительной информации.
Вы должны сделать ось видимой с помощью параметра chxt
, если хотите указать ее диапазон.
Чтобы указать значения настраиваемой оси, используйте параметр chxl
.
Синтаксис
Разделите диапазоны меток нескольких осей с помощью вертикальной черты ( |
).
chxr= <axis_index>,<start_val>,<end_val>,<opt_step> |...| <axis_index>,<start_val>,<end_val>,<opt_step>
- <индекс_оси >
- К какой оси применять метки. Это индекс, начинающийся с нуля, в массиве осей, заданном
chxt
. Например, ось r будет равна 1 вchxt=x,r,y
. - < начальное_значение >
- Число, определяющее нижнее значение для этой оси.
- < конечное_значение >
- Число, определяющее максимальное значение для этой оси.
- <opt_step>
- [ Необязательно ] Шаг отсчета между делениями на оси. Не существует значения шага по умолчанию; шаг рассчитан так, чтобы попытаться показать набор хорошо расположенных меток.
Примеры
Описание | Пример |
---|---|
В этом примере показаны левая и правая оси Y ( Каждая ось имеет определенный диапазон. Поскольку метки или позиции не указаны, значения берутся из заданного диапазона и равномерно распределяются внутри этого диапазона. На линейном графике значения равномерно распределены по оси X. Направление оси меняется на противоположное для оси r (индекс |
|
В этом примере значения указаны для оси X. Метки осей равномерно расположены вдоль оси. Для параметра <opt_step> указано значение пять ( | |
Пользовательские метки осей chxl
Вы можете указать собственные метки строковых осей на любой оси, используя параметр chxl
. Вы можете указать столько ярлыков, сколько захотите. Если вы отображаете ось (с помощью параметра chxt
) и не указываете пользовательские метки, будут применены стандартные числовые метки. Чтобы указать пользовательский числовой диапазон, используйте вместо этого параметр chxr
.
Чтобы установить определенные местоположения на оси для ваших меток, используйте параметр chxp
.
Синтаксис
Укажите один набор параметров для каждой оси, которую вы хотите пометить. Разделите несколько наборов меток с помощью вертикальной черты ( |
).
chxl= <axis_index>:|<label_1>|...|<label_n> |...| <axis_index>:|<label_1>|...|<label_n>
- <индекс_оси >
- К какой оси применять метки. Это индекс массива параметров
chxt
. Например, если у вас естьchxt=x,x,y,y
то индекс 0 будет первой осью X, а 1 — второй осью X. - <метка_1> | ... |< метка_n >
- Одна или несколько меток, которые можно разместить вдоль этой оси. Это могут быть строковые или числовые значения; строки не обязательно должны быть в кавычках. label_1 отображается в самой нижней позиции на оси, а label_n отображается в самой высокой позиции. Дополнительные метки располагаются между ними равномерно. Пробелы обозначайте знаком +. Невозможно указать разрыв строки в метке. Отдельные метки с помощью вертикальной черты. Примечание. Не размещайте трубку после последней метки в параметре
chxl
.
Примеры
Описание | Пример |
---|---|
На этой диаграмме показано, как добавлять пользовательские метки к двум осям. Обратите внимание, что значения расположены равномерно и что последнее значение | chxt=x,y |
Этот пример включает метки осей на левой и правой осях Y ( |
|
Этот пример включает метки осей на левой и правой осях Y ( В этом примере используются значения по умолчанию для меток оси на левой оси Y. |
|
Если вы хотите добавить общую метку для описания всей оси (например, чтобы пометить одну ось «стоимость», а другую — «студент»), используйте свойство | chxt=x,x,y,y |
Позиции меток осей chxp
Вы можете указать, какие метки осей отображать, используя метки по умолчанию или пользовательские метки, заданные с помощью chxl
. Если вы не укажете точные позиции с помощью этого параметра, метки будут располагаться равномерно и со значением шага по умолчанию вдоль осей. Если вы не укажете chxl
, метки делений будут значениями по умолчанию (обычно значениями данных или номерами столбцов в гистограммах).
Синтаксис
Разделите несколько наборов позиционирования с помощью вертикальной черты ( |
).
chxp= <axis_1_index>,<label_1_position>,...,<label_n_position> |...| <axis_m_index>,<label_1_position>,...,<label_n_position>
- <индекс_оси >
- Ось, для которой вы указываете позиции. Это индекс массива параметров
chxt
. Например, если у вас естьchxt=x,x,y,y
то индекс 0 будет первой осью X, 1 — второй осью X и так далее. - < label_1_position >,...,< label_n_position >
- Положение метки вдоль оси. Это список числовых значений, разделенных запятыми, где каждое значение задает положение соответствующей метки в массиве
chxl
: первая запись применяется к первой метке и так далее. Позиция — это значение в диапазоне для этой оси . Обратите внимание, что это всегда будет значение от 0 до 100, если вы не указали собственный диапазон с помощьюchxr
. У вас должно быть столько позиций, сколько меток для этой оси.
Примеры
Описание | Пример |
---|---|
Этот пример включает метки оси R в указанных позициях на диаграмме. Текст метки указывается с помощью параметра Метки с указанной позицией Метки с указанной позицией | |
В этом примере показано отображение значений меток по умолчанию, но только в указанных местах. |
chxt=x,y chxt=x,y chxp не указан |
Стили меток осей chxs
Вы можете указать размер, цвет и выравнивание шрифта для меток осей, как для пользовательских меток, так и для значений меток по умолчанию. Все метки на одной оси имеют одинаковый формат. Если у вас есть несколько копий оси, вы можете отформатировать каждую из них по-разному. Вы также можете указать формат строки метки, например, чтобы отображать символы валюты или конечные нули.
По умолчанию на верхней и нижней осях не отображаются деления значений, а на левой и правой осях они отображаются.
Синтаксис
Значения для нескольких осей следует разделять с помощью вертикальной черты ( |
).
chxs= <axis_index><opt_format_string>,<opt_label_color>,<opt_font_size>,<opt_alignment>,<opt_axis_or_tick>,<opt_tick_color>,<opt_axis_color> |...| <axis_index><opt_format_string>,<opt_label_color>,<opt_font_size>,<opt_alignment>,<opt_axis_or_tick>,<opt_tick_color>,<opt_axis_color>
- < индекс_оси >
- Ось, к которой это относится. Это индекс, отсчитываемый от нуля, в параметре
chxt
. - < строка_опт_формата >
- [ Необязательно ] Это необязательная строка формата, которая, если она используется, следует сразу после номера индекса оси без промежуточной запятой. Он начинается с буквы N, за которой следуют следующие значения (все необязательные):
N< preceding_text >*< number_type >< decimal_places >zs< x or y >*< following_text >
Вот значение каждого элемента:-
<preceding_text>
— буквенный текст, предшествующий каждому значению. -
*...*
— необязательный блок, заключенный в буквенные звездочки, в котором можно указать детали форматирования чисел. Следующие значения поддерживаются и являются необязательными:-
<number_type>
— числовой формат для числовых значений. Выберите один из следующих вариантов:-
f
- [ По умолчанию ] Формат с плавающей запятой. Рассмотрите также возможность указать точность с помощью значения < decimal_places >. -
p
— процентный формат. Знак % добавляется автоматически. Примечание. При использовании этого формата значения данных от 0,0 до 1,0 преобразуются в значения от 0 до 100 % (например, 0,43 будет отображаться как 43 %). -
e
- Формат научной записи. -
c< CUR >
— форматирует число в указанной валюте с соответствующим маркером валюты. Замените< CUR >
трехбуквенным кодом валюты. Пример:cEUR
для евро. Список кодов можно найти на веб-сайте ISO , хотя поддерживаются не все символы.
-
-
<decimal_places>
— целое число, определяющее количество отображаемых десятичных знаков. Значение округляется (не усекается) до этой длины. По умолчанию — 2. -
z
— отображать конечные нули. По умолчанию нет . -
s
— Отобразить разделители групп. По умолчанию нет . -
x
илиy
— отображение данных по координатам x или y, как указано. Значение данных x зависит от типа диаграммы: поэкспериментируйте с диаграммой, чтобы определить, что они означают. По умолчанию — «y» .
-
-
< following_text >
— буквенный текст, следующий за каждым значением.
-
- <opt_label_color>
- Цвет, применяемый к тексту оси (но не к линии оси) в шестнадцатеричном формате RRGGBB . Цвет линии оси указывается отдельно с помощью opt_axis_color . По умолчанию серый.
- < opt_font_size >
- [ Необязательно ] указывает размер шрифта в пикселях. Этот параметр является необязательным.
- <opt_alignment>
- [ Необязательно ] Выравнивание меток. Для верхней или нижней оси это описывает, как метка выравнивается по отметке над или под ней; для левой или правой осей это описывает, как выравнивается внутри ограничивающей рамки, которая касается оси. Укажите одно из следующих чисел:
-
-1
— Сверху или снизу : метки располагаются справа от галочек; Влево или вправо : метки в своей области выравниваются по левому краю. По умолчанию для меток оси R. -
0
— сверху или снизу : метки центрируются по меткам; Слева или справа : метки центрируются в своей области. По умолчанию для меток осей X и T. -
1
— Сверху или снизу : метки располагаются слева от галочек; Слева или справа : метки выравниваются по правому краю своей области. По умолчанию для меток оси Y.
-
- < opt_axis_or_tick >
- [ Необязательно; не поддерживается в Google-o-meter ] Показывать ли отметки и/или линии оси для этой оси. Засечки и оси доступны только для самых внутренних осей (например, они не поддерживаются для внешних из двух осей X). Используйте одно из следующих значений:
-
l
(строчная буква «L») — рисовать только линию оси. -
t
— рисовать только деления. Засечки — это маленькие линии рядом с метками осей. -
lt
- [ По умолчанию ] Нарисуйте линию оси и отметки для всех меток. -
_
- (подчеркивание) Не рисовать ни линию оси, ни деления. Если вы хотите скрыть линию оси, используйте это значение.
-
- < цвет_галочки >
- [ Необязательно ; не поддерживается в Google-o-meter ] Цвет отметки в шестнадцатеричном формате RRGGBB . По умолчанию серый.
- <opt_axis_color>
- [ Необязательно ] Цвет линии этой оси в шестнадцатеричном формате RRGGBB . По умолчанию серый.
Примеры
Описание | Пример |
---|---|
Font size and color are specified for the second x-axis (Jan, Feb, Mar). | |
Font size, color, and alignment are specified for the right y-axis. Tick marks, but no axis line, are drawn. | |
This chart includes three data sets, and shows three sets of axis labels, one per series. Each set of labels is formatted using a custom formatting string, as described here:
The axis label ranges are set using the | chd=s: |
Axis Tick Mark Styles chxtc
You can specify long tick marks for specific axes. Typically this is used to extend a tick mark across the length of a chart. Use the chxs
parameter to change the tick mark color.
Values for multiple axes should be separated using a pipe character ( |
). Values within a series should be separated by a comma.
Syntax
chxtc= <axis_index_1>,<tick_length_1>,...,<tick_length_n> |...| <axis_index_m>,<tick_length_1>,...,<tick_length_n>
- < axis_index >
- The axis to which this applies. This is a zero-based index into the
chxt
parameter. Separate values for different axes using a bar delimiter. - < tick_length_1 >,...,< tick_length_n >
- Length of the tick marks on that axis, in pixels. If a single value is given, it will apply to all values; if more than one value is given, the axis tick marks will cycle through the list of values for that axis. Positive values are drawn outside the chart area and cropped by the chart borders. The maximum positive value is 25. Negative values are drawn inside the chart area and cropped by the chart area borders.
Examples
Описание | Пример |
---|---|
Example of using
| |
This chart demonstrates alternating tick lengths. chxtc specifies two tick length values for the y-axis (5 and 15), and the ticks drawn on the chart alternate between the two values. | chxt=x,y |
Background Fills chf
[ All charts ]
You can specify fill colors and styles for the chart data area and/or the whole chart background. Fill types include solid fills, striped fills, and gradients. You can specify different fills for different areas (for example, the whole chart area, or just the data area). The chart area fill overwrites the background fill. All fills are specified using the chf
parameter, and you can mix different fill types (solids, stripes, gradients) in the same chart by separating values with pipe character ( | ). Chart area fills overwrite chart background fills.
Solid Fills chf
[ All Charts ]
You can specify a solid fill for the background and/or chart area, or assign a transparency value to the whole chart. You can specify multiple fills using the pipe character ( |
). (Maps: background only).
Syntax
chf=<fill_type>,s,<color>|...
- < fill_type >
- The part of the chart being filled. Specify one of the following values:
-
bg
- Background fill -
c
- Chart area fill. Not supported for map charts. -
a
- Make the whole chart (including backgrounds) transparent. The first six digits of< color >
are ignored, and only the last two (the transparency value) are applied to the whole chart and all fills. -
b <index>
- Bar solid fills (bar charts only). Replace < index > with the series index of the bars to fill with a solid color. The effect is similar to specifyingchco
in a bar chart. See Bar Chart Series Colors for an example.
-
- с
- Indicates a solid or transparency fill.
- < color >
- The fill color, in RRGGBB hexadecimal format . For transparencies, the first six digits are ignored, but must be included anyway.
Examples
Описание | Пример |
---|---|
This example fills the chart background with pale gray ( | |
This example fills the chart background with pale gray ( | |
This example applies a 50% transparency to the whole chart (80 in hexadecimal is 128, or about 50% transparency). Notice the table cell background showing through the chart. | |
Gradient Fills chf
[ Line, Bar, Google-o-meter, Radar, Scatter,Venn ]
You can apply one or more gradient fills to chart areas or backgrounds. Gradient fills are fades from a one color to another color. (Pie, Google-o-meter charts: background only.)
Each gradient fill specifies an angle, and then two or more colors anchored to a specified location. The color varies as it moves from one anchor to another. You must have at least two colors with different < color_centerpoint > values, so that one can fade into the other. Each additional gradient is specified by a < color >,< color_centerpoint > pair.
Syntax
chf=<fill_type>,lg,<angle>,<color_1>,<color_centerpoint_1> ,..., <color_n>,<color_centerpoint_n>
- < fill_type >
- The chart area to fill. One of the following:
-
bg
- Background fill -
c
- Chart area fill. -
b <index>
- Bar gradient fills (bar charts only). Replace < index > with the series index of the bars to fill with a gradient. See Bar Chart Series Colors for an example.
-
- lg
- Specifies a gradient fill.
- < angle >
- A number specifying the angle of the gradient from 0 (horizontal) to 90 (vertical).
- < color >
- The color of the fill, in RRGGBB hexadecimal format .
- < color_centerpoint >
- Specifies the anchor point for the color. The color will start to fade from this point as it approaches another anchor. The value range is from 0.0 (bottom or left edge) to 1.0 (top or right edge), tilted at the angle specified by < angle >.
Examples
Описание | Пример |
---|---|
Chart area has a horizontal linear gradient, specified with an angle of zero degrees ( The colors are peach ( The chart background is drawn in gray ( | |
Chart area has a diagonal (bottom left to top right) linear gradient, specified with an angle of forty-five degrees ( Peach ( Blue ( The chart background is drawn in gray ( | |
Chart area has a vertical (top to bottom) linear gradient, specified with an angle of ninety degrees ( Blue ( Peach ( The chart background is drawn in gray ( | |
Striped fills chf
[ Line, Bar, Google-o-meter, Radar, Scatter, Venn ]
You can specify a striped background fill for your chart area, or the whole chart. (Pie, Google-o-meter charts: background only.)
Syntax
chf= <fill_type>,ls,<angle>,<color_1>,<width_1> ,..., <color_n>,<width_n>
- < fill_type >
- The chart area to fill. One of the following:
-
bg
- Background fill -
c
- Chart area fill -
b <index>
- Bar striped fills (bar charts only). Replace < index > with the series index of the bars to fill with stripes. See Bar Chart Series Colors for an example.
-
- ls
- Specifies linear stripe fill.
- < angle >
- The angle of all stripes, relative to the y-axis. Use
0
for vertical stripes or90
for horizontal stripes. - < color >
- The color for this stripe, in RRGGBB hexadecimal format . Repeat < color > and < width > for each additional stripe. You must have at least two stripes. Stripes alternate until the chart is filled.
- < width >
- The width of this stripe, from
0
to1
, where1
is the full width of the chart. Stripes are repeated until the chart is filled. Repeat < color > and < width > for each additional stripe. You must have at least two stripes. Stripes alternate until the chart is filled.
Examples
Описание | Пример |
---|---|
| chf= |
| chf= |
Data Functions chfd
[ All chd
charts ]
You can specify a custom function to run over chart data using muParser function syntax . The data used in the function can come from one of two sources:
- A data series from
chd
- The data is pulled from the specified series inchd
. - A range of values declared in the
chfd
parameter itself - You declare a start, stop, and step value for an arbitrary data range.
It is important to note that in all cases you must assign the output to an existing series in chd
; that series will be overwritten by the function output. The chart is rendered only after all functions have been processes, so if you assign multiple functions to output to the same data series, the functions will be run in the order given, but only the output of the final function will be plotted on the chart. Note that you can chain functions, so that one function can take as input a series that was output by a previous function.
To assign colors or chm
markers to a function line, assign the colors or markers to the function's series index. Note that markers are placed according to the data after it has been manipulated by the function.
Syntax
chfd= <output_series_index>,<function_data>,<function_string> |...| <output_series_index>,<function_data>,<function_string>
- < output_series_index >
- Zero-based index of a data series in
chd
to which the function output will be written. Any existing data will be completely overwritten by the function output. If a series is not being used as input for a function, best practice is to assign a single dummy value to that series. - < function_data >
- The variables and data to plot. The data can be from a range that you define, or from one of the
chd
data series. You can specify multiple variables for each function, using a ; (semicolon) delimiter for multiple variables. Note that if you define multiple variables for a single function, and these variables have a different number of points, the function will stop when it reaches the first endpoint. For example, if a function defines both x=1—5 step 1 and y=1—10 step 1, the function will end when it reaches the fifth point.
< variable_name >,< input_series_index >
OR
< variable_name >,< start >,< end >,< step >
- variable_name - An arbitrary string name for the variable. Use this in the function defined by function_string .
- input_series_index - The index of a
chd
data series to use as input data. - start - The numeric start value of a range.
- end - The numeric end value of a range.
- step - The numeric step value from start to end . Can be positive or negative, but cannot be zero.
x,0,100,1
declares a variable namedx
with values 0, 1, 2, ... 100.x,0,100,1;r,0,3.1,.1
declares the samex
variable plus a variable namedr
with values 0, 0.1, 0.2, ..., 3.0, 3.1.x,0
declares a variable named x that uses the data from the firstchd
series. These variables will be used by function_string . They will not be plotted on the graph unless you specify them in function_string . The smaller the step, the smoother your graph. - < function_string >
- Your function, written in the muParser syntax . The function is applied to the variables and data specified in variable_data . You can only reference the variables declared in this local function set, not in another piped set of
chfd
parameters. Summary muParser functions are not supported (min, max sum, avg). IMPORTANT: Remember to use%2B
instead of+
in your functions!
Examples
Описание | Пример |
---|---|
A simple sine wave. Some things to notice:
| cht=lc |
This line uses data from the chd parameter. | chd=t:5,10 |
A mix of function and non-function lines. Notice how the colors are specified by the series color parameter Notice the placement of markers on the function output; the data points are calculated from start , end , and step , so if your range is 0—11 step 0.1, point 0 is 0, point 1 is 0.1 and so on, until point 110, which has a value of 11. | chd=t: |
To define a function in two dimensions, use an
| cht=lxy |
The Try clicking these images to open and play with them in the chart playground; you'll get hooked! |
This document describes how to create pie charts using the Chart API.
Table of Contents
Chart-Specific Features
| Standard Features
|
Обзор
Pie charts are good for showing simple proportional part-to-whole information. You can create a single series pie chart, where each series is made of multiple slices, or multi-series, concentric charts.
Each series describes one pie, and each data value specifies one slice. When using nested pie charts (described below), use multiple series.
To display the text associated with a slice, you will have to use either pie chart labels or a chart legend . Pie chart labels are text around the chart with lines pointing toward the slice. Legends are text associated by color.
Labels | Легенда | Labels and Legend |
---|---|---|
chl=January|February|March|April | chdl=January|February|March|April | chl=January|February|March|April |
Values are displayed relative to each other: so a chart with values 1,2,3 will look the same as a chart with values 100,200,300. However, when using text format data, values greater than 100 are trimmed to 100, so you will need to use text format with custom scaling to display slices greater than 100 properly (use the chds
parameter with min/max values of chds=0,< max-slice-size >
).
Negative values display as empty slices of the appropriate size.
Chart Types
There are three general types of pie charts that you can create: flat, concentric, or 3D. Specify a pie chart with the following syntax:
Syntax
cht=<chart_type>
Where < chart_type >
is one of the the following types:
Parameter | Описание | Пример |
---|---|---|
| Two dimensional pie chart. Supply one data series only; subsequent data series are ignored. By default, pie segment colors are interpolated from dark orange to pale yellow. Specify other colors as described in Series Colors . Specify labels with The Google Chart API calculates the circle's radius from the minimum of width and height specified in the chart size ( | |
| A three-dimensional pie chart. Specify data and formatting in the same way as for two dimensional pie charts, above. If you are including labels in a three-dimensional pie chart, you probably need to specify the size of the width to be 2.5 times the size of the height, to ensure that your labels are fully visible. | |
| A concentric pie chart. Supply two or more data series. | |
All types | Negative numbers in data cause "blank" slices. | cht=pc |
Series Colors chco
You can specify the colors of all values, each value, or some values using the chco
parameter.
Syntax
chco=<slice_1>|<slice_2>|<slice_n>,<series_color_1>,...,<series_color_n>
- < color >
- Slice colors in RRGGBB hexadecimal format . Specify a single series color and all slices in that series will be colored in gradations of that color from darkest (first data member) to lightest (last data member). Specify two or more colors delimited by a | to describe individual slice colors. When you have multiple series (that is, a chart with concentric rings), you can specify values for different series by separating values by a comma. When fewer slice/series colors are given than slices/series displayed, then the chart will cycle through from the beginning of the slice list for the series, or the series list for the chart. You cannot specify a distinct gradient for each series in a multi-series chart.
Описание | Пример |
---|---|
Specify a single color to have gradations from darkest (first slice) to lightest (last slice). | |
Defining a gradient; here, from yellow to red. |
|
Defining individual slice colors; specify one color per slice. | chd=t:10,20,30 |
This chart has two data series, but specifies color as a single gradient across all slices from yellow to red (BBBB00—BB0000). | chco=BBBB00,BB0000 |
Here's a concentric chart that includes both series colors and individual slice colors. The chart has two concentric data series. In human-readable form, the colors are chco=green|red,blue|yellow. The comma breaks this into two series:
| chd=s:eYY,ORVM |
Pie Chart Labels chl
You can specify labels for individual pie chart slices using the chl
parameter. You can also display a legend with the same or different values, one legend entry per slice.
A Note on String Values: Only URL-safe characters are permitted in label strings. To be safe, you should URL-encode any strings containing characters not in the character set 0-9a-zA-Z
. You can find a URL encoder here .
Syntax
chl= <label_value>| ... <label_value>
- <label_value >
- A string value to apply to a slice. Labels are applied consecutively to the data points in
chd
. If you have multiple series (for a concentric pie chart, for example), labels are applied to all points in all sequences, in the order specified inchd
. Use a pipe delimiter (|
) between each label. Specify a missing intervening value by using two consecutive pipe characters with no space between them:||
. You do not need to label all slices.
Examples
Описание | Пример |
---|---|
Labels for a three-dimensional pie chart. | |
When specifying the size of your chart with Generally, a two-dimensional pie chart needs to be approximately twice as wide as it is high, and a three-dimensional pie chart needs to be approximately two and a half times wider than it is high, to display labels properly. In the first example, the labels are only partially displayed, because the chart is not wide enough. The second example shows that the chart needs a width of 280 pixels to display the labels in full. (Borders added explicitly to the | |
Pie Chart Rotation chp
By default, the first series is drawn starting at 3:00, continuing clockwise around the chart, but you can specify a custom rotation using the chp
parameter.
Syntax
chp=<radians>
- <radians >
- A floating point value describing how many radians to rotate the chart clockwise. One complete turn is 2 π (2 pi—about 6.28) radians.
Examples
Описание | Пример |
---|---|
To change the orientation of a pie chart, use | |
Here's another example of pie chart rotations. These can be combined with chart shape markers to create some interesting effects . |
Standard Features
The rest of the features on this page are standard chart features.
Chart Title chtt
, chts
[ All charts ]
You can specify the title text, color, and font size for your chart.
Syntax
chtt=<chart_title> chts=<color>,<font_size>,<opt_alignment>
chtt
- Specifies the chart title.
- < chart_title >
- Title to show for the chart. You cannot specify where this appears, but you can optionally specify the font size and color. Use a + sign to indicate spaces, and a pipe character (
|
) to indicate line breaks.
chts
[ Optional ] - Colors and font size for the chtt
parameter.
- <color >
- The title color, in RRGGBB hexadecimal format . Default color is black.
- <font_size >
- Font size of the title, in points.
- < opt_alignment >
- [ Optional ] Alignment of the title. Choose one of the following case-sensitive string values: "l" (left), "c" (centered) "r" (right). Default is "c".
Examples
Описание | Пример |
---|---|
A chart with a title, using default color and font size. Specify a space with a plus sign ( Use a pipe character ( | chtt=Site+visitors+by+month| |
A chart with a blue, right-aligned, 20-point title. | chtt=Site+visitors |
Chart Legend Text and Style chdl
, chdlp
, chdls
[ All charts ]
The legend is a side section of the chart that gives a small text description of each series. You can specify the text associated with each series in this legend, and specify where on the chart it should appear.
See also chma
, to learn how to set the margins around your legend.
A note on string values: Only URL-safe characters are permitted in label strings. To be safe, you should URL-encode any strings containing characters not in the character set 0-9a-zA-Z
. You can find a URL encoder in the Google Visualization Documentation .
Syntax
chdl=<data_series_1_label>|...|<data_series_n_label> chdlp=<opt_position>|<opt_label_order> chdls=<color>,<size>
chdl
- The text for each series, to display in the legend.
- < data_series_label >
- The text for the legend entries. Each label applies to the corresponding series in the
chd
array. Use a + mark for a space. If you do not specify this parameter, the chart will not get a legend. There is no way to specify a line break in a label. The legend will typically expand to hold your legend text, and the chart area will shrink to accommodate the legend.
chdlp
- [ Optional ] The position of the legend, and order of the legend entries. You can specify < position > and/or < label_order >. If you specify both, separate them with a bar character. You can add an 's' to any value if you want empty legend entries in chdl
to be skipped in the legend. Examples: chdlp=bv
, chdlp=r
, chdlp=bv|r
, chdlp=bvs|r
- < opt_position >
- [ Optional ] Specifies the position of the legend on the chart. To specify additional padding between the legend and the chart area or the image border, use the
chma
parameter. Choose one of the following values:-
b
- Legend at the bottom of the chart, legend entries in a horizontal row. -
bv
- Legend at the bottom of the chart, legend entries in a vertical column. -
t
- Legend at the top of the chart, legend entries in a horizontal row. -
tv
- Legend at the top of the chart, legend entries in a vertical column. -
r
- [ Default ] Legend to the right of the chart, legend entries in a vertical column. -
l
- Legend to the left of the chart, legend entries in a vertical column.
-
- < opt_label_order >
- [ Optional ] The order in which the labels are shown in the legend. Choose one of the following value:
-
l
- [ Default for vertical legends ] Display labels in the order given tochdl
. -
r
- Display labels in the reverse order as given tochdl
. This is useful in stacked bar charts to show the legend
in the same order as the bars appear. -
a
- [ Default for horizontal legends ] Automatic ordering: roughly means sorting by length, shortest first, as measured in 10 pixel blocks. When two elements are the same length (divided into 10 pixel blocks), the one listed first will appear first. -
0,1,2...
- Custom label order. This is a list of zero-based label indexes fromchdl
, separated by commas.
-
chdls
- [ Optional ] Specifies the color and font size of the legend text.
- < color >
- The legend text color, in RRGGBB hexadecimal format .
- < size >
- The point size of the legend text.
Examples
Описание | Пример |
---|---|
Two examples of legends. Specify legend text in the same order as your data series. | chdl=NASDAQ|FTSE100|DOW chdl=First|Second|Third |
The first chart demonstrates horizontal legend entries ( | |
This example demonstrates changing the font size. | |
Chart Margins chma
[ All charts ]
You can specify the size of the chart's margins, in pixels. Margins are calculated inward from the specified chart size ( chs
); increasing the margin size does not increase the total chart size, but rather shrinks the chart area, if necessary.
The margins are by default whatever is left over after the chart size is calculated. This default value varies by chart type. The margins that you specify are a minimum value; if the chart area leaves room for margins, the margin size will be whatever is left over; you cannot squeeze the margins smaller than what is required for any legends and labels. Here's a diagram showing the basic parts of a chart:
The chart margins include the axis labels and the legend area . The legend area resizes automatically to fit the text exactly, unless you specify a larger width using Tip: In a bar chart, if the bars have a fixed size (the default), the chart area width cannot be reduced. You must specify a smaller or resizeable bar size using |
Syntax
chma= <left_margin>,<right_margin>,<top_margin>,<bottom_margin>|<opt_legend_width>,<opt_legend_height>
- < left_margin >, < right_margin >, < top_margin >, < bottom_margin >
- Minimum margin size around the chart area, in pixels. Increase this value to include some padding to prevent axis labels from bumping against the borders of the chart.
- < opt_legend_width >, < opt_legend_height >
- [ Optional ] Width of the margin around the legend, in pixels. Use this to avoid having the legend bump up against the chart area or the edges of the image.
Examples
Описание | Пример |
---|---|
In this example, the chart has a minimum margin of 30 pixels on each side. Because the chart legend is more than 30 pixels wide, the margin on the right side is set to the width of the chart legend, and is different from the other margins. Axis labels are outside the plot area, and are therefore drawn within the margin space. |
|
To add a margin around the legend, set a value for the In this example, the legend is approximately 60 pixels wide. If you set the the |
|
Axis Styles and Labels [ Line, Bar, Google-o-meter, Radar, Scatter ]
You can specify which axes to display on the chart, and give them custom labels and positions, ranges, and styles.
Not all charts show axis lines by default. You can specify exactly which axes your chart should show using the chxt
parameter. Default axis lines do not show numbers; you must specify an axis in the chxt
parameter to show numbers.
You can choose to have your axes display numbers reflecting the data values, or you can specify custom axes. The default is to display numeric values, with values scaled to range from 0—100. However, you can change that range using chxr
to display any range, and you can style the values (for example, to show currency symbols or decimal places) using chxs
.
If you choose to use custom values, for example: "Mon, Tues, Wed", you can use the chxl
parameter. To place these labels in specific locations along the axis, use the chxp
parameter.
Finally, you can use the chxs
and chxtc
parameters to specify color, size, alignment, and other properties of both custom and numeric axis labels.
A note on string values: Only URL-safe characters are permitted in label strings. To be safe, you should URL-encode any strings containing characters not in the character set 0-9a-zA-Z
. You can find a URL encoder in the Google Visualization Documentation .
This section covers the following topics:
- Visible Axes (
chxt
) - Which axes to display. - Axis range (
chxr
) - Value range for each axis. - Custom Axis Labels (
chxl
) - Custom values to show on the axis. - Axis label positions (
chxp
) - Placement of custom labels along each axis. - Axis label styles (
chxs
) - Color, size, alignment, and formatting of axis labels. - Axis tick mark styles (
chxtc
) - Length of tick marks for a specific axis.
Visible Axes chxt
Bar, line, radar, and scatter charts show one or two axis lines by default, but these lines do not include values. To display values on your axis lines, or to change which axes are shown, you must use the chxt
parameter. By default, the axis values range from 0-100, unless you scale them explicitly using the chxr
property. To hide all axis lines in a line chart, specify :nda
after the chart type value in the cht
parameter (example: cht= lc:nda
).
By default, the top and bottom axes do not show tick marks by the values, while the left and right axes do show them. You can change this behavior using the chxs
parameter.
Syntax
chxt= <axis_1> ,..., <axis_n>
- < axis >
- An axis to show on the chart. Available axes are:
-
x
- Bottom x-axis -
t
- Top x-axis [ Not supported by Google-o-Meter ] -
y
- Left y-axis -
r
- Right y-axis [ Not supported by Google-o-Meter ]
-
You can specify multiple axes of the same type, for example: cht=x,x,y
. This will stack two sets of x-axes along the bottom of the chart. This is useful when adding custom labels along an axis that shows numeric values (see the example below). Axes are drawn from the inside out, so if you have x,x
, the first x refers to the innermost copy, the next x refers to the next outwards copy, and so on.
Examples
Описание | Пример |
---|---|
This example shows a line chart with an x-axis, a y-axis, a top axis (t), and a right axis (r). Because no labels are specified, the chart defaults to a range of 0 to 100 for all axes. Note that by default, the top and bottom axes don't show tick marks by the labels. |
|
You can include multiple sets of labels for each axis by including the same value more than once. This example shows two sets of x and two sets of y-axes. This isn't particularly useful when using only the default axis labels, as is shown here. But you can specify custom labels for each copy of each axis, using the chxl parameter. | chxt=x,x,y,y chxt=x,x,y,y |
This example shows a horizontal bar chart with an x-axis, a y-axis, an upper t-axis, and a right r-axis. Axis labels are omitted, so the Chart API displays a range of 0 to 100 for the x-axis and for the t-axis. The range for the y-axis and for the r-axis is determined by the number of bars. In this case, there are five bars, so the Chart API displays a range of 0 to 4. The first label is centered at the base of the first bar, the second label is centered at the base of the second bar, and so on. |
|
You can suppress default axes in a line chart by specifying :nda after the chart type. | cht=lc:nda |
Axis Range chxr
You can specify the range of values that appear on each axis independently, using the chxr parameter. Note that this does not change the scale of the chart elements, only the scale of the axis labels. If you want to make the axis numbers describe the actual data values, set < start_val > and < end_val > to the lower and upper values of your data format range, respectively. See Axis Scaling for more information.
You must make an axis visible using the chxt
parameter if you want to specify its range.
To specify custom axis values, use the chxl
parameter.
Syntax
Separate multiple axis label ranges using the pipe character ( |
).
chxr= <axis_index>,<start_val>,<end_val>,<opt_step> |...| <axis_index>,<start_val>,<end_val>,<opt_step>
- <axis_index >
- Which axis to apply the labels to. This is a zero-based index into the axis array specified by
chxt
. For example, the r-axis would be 1 inchxt=x,r,y
. - < start_val >
- A number, defining the low value for this axis.
- < end_val >
- A number, defining the high value for this axis.
- < opt_step >
- [ Optional ] The count step between ticks on the axis. There is no default step value; the step is calculated to try to show a set of nicely spaced labels.
Examples
Описание | Пример |
---|---|
This example shows left and right y-axes ( Each axis has a defined range. Because no labels or positions are specified, values are taken from the given range, and are evenly spaced within that range. In the line chart, values are evenly spread along the x-axis. Axis direction is reversed for the r-axis (index |
|
In this example, values are specified for the x-axis. Axis labels are evenly spaced along the axis. A value of five ( | |
Custom Axis Labels chxl
You can specify custom string axis labels on any axis, using the chxl
parameter. You can specify as many labels as you like. If you display an axis (using the chxt
parameter) and do not specify custom labels, the standard, numeric labels will be applied. To specify a custom numeric range, use the chxr
parameter instead.
To set specific locations along the axis for your labels, use the chxp
parameter.
Syntax
Specify one parameter set for each axis that you want to label. Separate multiple sets of labels using the pipe character ( |
).
chxl= <axis_index>:|<label_1>|...|<label_n> |...| <axis_index>:|<label_1>|...|<label_n>
- <axis_index >
- Which axis to apply labels to. This is an index into the
chxt
parameter array. For example, if you havechxt=x,x,y,y
then index 0 would be the first x-axis, 1 would be the second x-axis. - <label_1> | ... |< label_n >
- One or more labels to place along this axis. These can be string or number values; strings do not need to be in quotes. label_1 is displayed at the lowest position on the axis, and label_n is displayed at the highest position. Additional labels are spaced evenly between them. Indicate spaces with a + mark. There is no way to specify a line break in a label. Separate labels with a pipe character. Note: Do not place a pipe after the final label in the
chxl
parameter.
Examples
Описание | Пример |
---|---|
This chart shows how to add custom labels to two axes. Note how the values are evenly spaced, and how the last | chxt=x,y |
This example includes axis labels on the left and right y-axes ( |
|
This example includes axis labels on the left and right y-axes ( This example uses default values for the axis labels on the left y-axis. |
|
If you want to add a generic label to describe a whole axis (for example, to label one axis "cost" and another "student"), use the | chxt=x,x,y,y |
Axis Label Positions chxp
You can specify which axis labels to show, whether using the default labels or custom labels specified using chxl
. If you do not specify exact positions using this parameter, labels will be spaced evenly and at a default step value along the axes. If you do not specify chxl
, then the tick mark labels will be the default values (typically data values, or the bar numbers in bar charts).
Syntax
Separate multiple positioning sets using the pipe character ( |
).
chxp= <axis_1_index>,<label_1_position>,...,<label_n_position> |...| <axis_m_index>,<label_1_position>,...,<label_n_position>
- <axis_index >
- The axis for which you are specifying positions. This is an index into the
chxt
parameter array. For example, if you havechxt=x,x,y,y
then index 0 would be the first x-axis, 1 would be the second x-axis, and so on. - < label_1_position >,...,< label_n_position >
- The position of the label along the axis. This is a comma-separated list of numeric values, where each value sets the position of the corresponding label in the
chxl
array: the first entry applies to the first label, and so on. The position is a value in the range for that axis . Note that this will always be 0—100 unless you have specified a custom range usingchxr
. You must have as many positions as you have labels for that axis.
Examples
Описание | Пример |
---|---|
This example includes r-axis labels at specified positions on the chart. The label text is specified using the Labels with a specified position of Labels with a specified position of | |
This example demonstrates showing the default label values, but only at specified locations. |
chxt=x,y chxt=x,y chxp not specified |
Axis Label Styles chxs
You can specify the font size, color, and alignment for axis labels, both custom labels and default label values. All labels on the same axis have the same format. If you have multiple copies of an axis, you can format each one differently. You can also specify the format of a label string, for example to show currency symbols or trailing zeroes.
By default, the top and bottom axes do not show tick marks by the values, while the left and right axes do show them.
Syntax
Values for multiple axes should be separated using a pipe character ( |
).
chxs= <axis_index><opt_format_string>,<opt_label_color>,<opt_font_size>,<opt_alignment>,<opt_axis_or_tick>,<opt_tick_color>,<opt_axis_color> |...| <axis_index><opt_format_string>,<opt_label_color>,<opt_font_size>,<opt_alignment>,<opt_axis_or_tick>,<opt_tick_color>,<opt_axis_color>
- < axis_index >
- The axis to which this applies. This is a zero-based index into the
chxt
parameter. - < opt_format_string >
- [ Optional ] This is an optional format string that, if used, follows immediately after the axis index number without an intervening comma. It starts with a literal letter N followed by the following values, all optional:
N< preceding_text >*< number_type >< decimal_places >zs< x or y >*< following_text >
Here is the meaning of each element:-
<preceding_text>
- Literal text to precede each value. -
*...*
- An optional block wrapped in literal asterisks, in which you can specify formatting details for numbers. The following values are supported, and are all optional:-
<number_type>
- The number format, for numeric values. Choose one of the following:-
f
- [ Default ] Floating point format. Consider specifying precision as well with the < decimal_places > value. -
p
- Percentage format. A % sign is appended automatically. Note: When using this format, data values from 0.0 — 1.0 map to 0 — 100% (for example, 0.43 will be shown as 43%). -
e
- Scientific notation format. -
c< CUR >
- Format the number in the currency specified, with the appropriate currency marker. Replace< CUR >
with a three-letter currency code. Example:cEUR
for Euros. You can find a list of codes on the ISO web site , although not all symbols are supported.
-
-
<decimal_places>
- An integer specifying how many decimal places to show. The value is rounded (not truncated) to this length. Default is 2. -
z
- Display trailing zeros. Default is no . -
s
- Display group separators. Default is no . -
x
ory
-Display the data from the x- or y-coordinate, as specified. The meaning of x data varies by chart type: experiment with your chart to determine what it means. Default is 'y' .
-
-
< following_text >
- Literal text to follow each value.
-
- < opt_label_color >
- The color to apply to the axis text (but not axis line), in RRGGBB hexadecimal format . Axis line color is specified separately using opt_axis_color . Default is gray.
- < opt_font_size >
- [ Optional ] specifies the font size in pixels. This parameter is optional.
- < opt_alignment >
- [ Optional ] Label alignment. For top or bottom axes, this describes how the label aligns to the tick mark above or below it; for left or right axes, this describes how the aligns inside its bounding box, which touches the axis. Specify one of the following numbers:
-
-1
- Top or bottom : labels are to the right of the ticks; Left or right : labels are left-aligned in their area. Default for r-axis labels. -
0
- Top or bottom : labels are centered on the ticks; Left or right : labels are centered in their area. Default for x- and t-axis labels. -
1
- Top or bottom : labels are to the left of the ticks; Left or right : labels are right-aligned in their area. Default for y-axis labels.
-
- < opt_axis_or_tick >
- [ Optional; not supported in Google-o-meter ] Whether to show tick marks and/or axis lines for this axis. Tick marks and axis lines are only available for innermost axes (for example, they are not supported for the outer of two x-axes). Use one of the following values:
-
l
(lowercase 'L') - Draw axis line only. -
t
- Draw tick marks only. Tick marks are the little lines next to axis labels. -
lt
- [ Default ] Draw both an axis line and tick marks for all labels. -
_
- (Underscore) Draw neither axis line nor tick marks. If you want to hide an axis line, use this value.
-
- < tick_color >
- [ Optional ; not supported in Google-o-meter ] The tick mark color, in RRGGBB hexadecimal format . Default is gray.
- < opt_axis_color >
- [ Optional ] The color of this axis line, in RRGGBB hexadecimal format . Default is gray.
Examples
Описание | Пример |
---|---|
Font size and color are specified for the second x-axis (Jan, Feb, Mar). | |
Font size, color, and alignment are specified for the right y-axis. Tick marks, but no axis line, are drawn. | |
This chart includes three data sets, and shows three sets of axis labels, one per series. Each set of labels is formatted using a custom formatting string, as described here:
The axis label ranges are set using the | chd=s: |
Axis Tick Mark Styles chxtc
You can specify long tick marks for specific axes. Typically this is used to extend a tick mark across the length of a chart. Use the chxs
parameter to change the tick mark color.
Values for multiple axes should be separated using a pipe character ( |
). Values within a series should be separated by a comma.
Syntax
chxtc= <axis_index_1>,<tick_length_1>,...,<tick_length_n> |...| <axis_index_m>,<tick_length_1>,...,<tick_length_n>
- < axis_index >
- The axis to which this applies. This is a zero-based index into the
chxt
parameter. Separate values for different axes using a bar delimiter. - < tick_length_1 >,...,< tick_length_n >
- Length of the tick marks on that axis, in pixels. If a single value is given, it will apply to all values; if more than one value is given, the axis tick marks will cycle through the list of values for that axis. Positive values are drawn outside the chart area and cropped by the chart borders. The maximum positive value is 25. Negative values are drawn inside the chart area and cropped by the chart area borders.
Examples
Описание | Пример |
---|---|
Example of using
| |
This chart demonstrates alternating tick lengths. chxtc specifies two tick length values for the y-axis (5 and 15), and the ticks drawn on the chart alternate between the two values. | chxt=x,y |
Background Fills chf
[ All charts ]
You can specify fill colors and styles for the chart data area and/or the whole chart background. Fill types include solid fills, striped fills, and gradients. You can specify different fills for different areas (for example, the whole chart area, or just the data area). The chart area fill overwrites the background fill. All fills are specified using the chf
parameter, and you can mix different fill types (solids, stripes, gradients) in the same chart by separating values with pipe character ( | ). Chart area fills overwrite chart background fills.
Solid Fills chf
[ All Charts ]
You can specify a solid fill for the background and/or chart area, or assign a transparency value to the whole chart. You can specify multiple fills using the pipe character ( |
). (Maps: background only).
Syntax
chf=<fill_type>,s,<color>|...
- < fill_type >
- The part of the chart being filled. Specify one of the following values:
-
bg
- Background fill -
c
- Chart area fill. Not supported for map charts. -
a
- Make the whole chart (including backgrounds) transparent. The first six digits of< color >
are ignored, and only the last two (the transparency value) are applied to the whole chart and all fills. -
b <index>
- Bar solid fills (bar charts only). Replace < index > with the series index of the bars to fill with a solid color. The effect is similar to specifyingchco
in a bar chart. See Bar Chart Series Colors for an example.
-
- с
- Indicates a solid or transparency fill.
- < color >
- The fill color, in RRGGBB hexadecimal format . For transparencies, the first six digits are ignored, but must be included anyway.
Examples
Описание | Пример |
---|---|
This example fills the chart background with pale gray ( | |
This example fills the chart background with pale gray ( | |
This example applies a 50% transparency to the whole chart (80 in hexadecimal is 128, or about 50% transparency). Notice the table cell background showing through the chart. | |
Gradient Fills chf
[ Line, Bar, Google-o-meter, Radar, Scatter,Venn ]
You can apply one or more gradient fills to chart areas or backgrounds. Gradient fills are fades from a one color to another color. (Pie, Google-o-meter charts: background only.)
Each gradient fill specifies an angle, and then two or more colors anchored to a specified location. The color varies as it moves from one anchor to another. You must have at least two colors with different < color_centerpoint > values, so that one can fade into the other. Each additional gradient is specified by a < color >,< color_centerpoint > pair.
Syntax
chf=<fill_type>,lg,<angle>,<color_1>,<color_centerpoint_1> ,..., <color_n>,<color_centerpoint_n>
- < fill_type >
- The chart area to fill. One of the following:
-
bg
- Background fill -
c
- Chart area fill. -
b <index>
- Bar gradient fills (bar charts only). Replace < index > with the series index of the bars to fill with a gradient. See Bar Chart Series Colors for an example.
-
- lg
- Specifies a gradient fill.
- < angle >
- A number specifying the angle of the gradient from 0 (horizontal) to 90 (vertical).
- < color >
- The color of the fill, in RRGGBB hexadecimal format .
- < color_centerpoint >
- Specifies the anchor point for the color. The color will start to fade from this point as it approaches another anchor. The value range is from 0.0 (bottom or left edge) to 1.0 (top or right edge), tilted at the angle specified by < angle >.
Examples
Описание | Пример |
---|---|
Chart area has a horizontal linear gradient, specified with an angle of zero degrees ( The colors are peach ( The chart background is drawn in gray ( | |
Chart area has a diagonal (bottom left to top right) linear gradient, specified with an angle of forty-five degrees ( Peach ( Blue ( The chart background is drawn in gray ( | |
Chart area has a vertical (top to bottom) linear gradient, specified with an angle of ninety degrees ( Blue ( Peach ( The chart background is drawn in gray ( | |
Striped fills chf
[ Line, Bar, Google-o-meter, Radar, Scatter, Venn ]
You can specify a striped background fill for your chart area, or the whole chart. (Pie, Google-o-meter charts: background only.)
Syntax
chf= <fill_type>,ls,<angle>,<color_1>,<width_1> ,..., <color_n>,<width_n>
- < fill_type >
- The chart area to fill. One of the following:
-
bg
- Background fill -
c
- Chart area fill -
b <index>
- Bar striped fills (bar charts only). Replace < index > with the series index of the bars to fill with stripes. See Bar Chart Series Colors for an example.
-
- ls
- Specifies linear stripe fill.
- < angle >
- The angle of all stripes, relative to the y-axis. Use
0
for vertical stripes or90
for horizontal stripes. - < color >
- The color for this stripe, in RRGGBB hexadecimal format . Repeat < color > and < width > for each additional stripe. You must have at least two stripes. Stripes alternate until the chart is filled.
- < width >
- The width of this stripe, from
0
to1
, where1
is the full width of the chart. Stripes are repeated until the chart is filled. Repeat < color > and < width > for each additional stripe. You must have at least two stripes. Stripes alternate until the chart is filled.
Examples
Описание | Пример |
---|---|
| chf= |
| chf= |
Data Functions chfd
[ All chd
charts ]
You can specify a custom function to run over chart data using muParser function syntax . The data used in the function can come from one of two sources:
- A data series from
chd
- The data is pulled from the specified series inchd
. - A range of values declared in the
chfd
parameter itself - You declare a start, stop, and step value for an arbitrary data range.
It is important to note that in all cases you must assign the output to an existing series in chd
; that series will be overwritten by the function output. The chart is rendered only after all functions have been processes, so if you assign multiple functions to output to the same data series, the functions will be run in the order given, but only the output of the final function will be plotted on the chart. Note that you can chain functions, so that one function can take as input a series that was output by a previous function.
To assign colors or chm
markers to a function line, assign the colors or markers to the function's series index. Note that markers are placed according to the data after it has been manipulated by the function.
Syntax
chfd= <output_series_index>,<function_data>,<function_string> |...| <output_series_index>,<function_data>,<function_string>
- < output_series_index >
- Zero-based index of a data series in
chd
to which the function output will be written. Any existing data will be completely overwritten by the function output. If a series is not being used as input for a function, best practice is to assign a single dummy value to that series. - < function_data >
- The variables and data to plot. The data can be from a range that you define, or from one of the
chd
data series. You can specify multiple variables for each function, using a ; (semicolon) delimiter for multiple variables. Note that if you define multiple variables for a single function, and these variables have a different number of points, the function will stop when it reaches the first endpoint. For example, if a function defines both x=1—5 step 1 and y=1—10 step 1, the function will end when it reaches the fifth point.
< variable_name >,< input_series_index >
OR
< variable_name >,< start >,< end >,< step >
- variable_name - An arbitrary string name for the variable. Use this in the function defined by function_string .
- input_series_index - The index of a
chd
data series to use as input data. - start - The numeric start value of a range.
- end - The numeric end value of a range.
- step - The numeric step value from start to end . Can be positive or negative, but cannot be zero.
x,0,100,1
declares a variable namedx
with values 0, 1, 2, ... 100.x,0,100,1;r,0,3.1,.1
declares the samex
variable plus a variable namedr
with values 0, 0.1, 0.2, ..., 3.0, 3.1.x,0
declares a variable named x that uses the data from the firstchd
series. These variables will be used by function_string . They will not be plotted on the graph unless you specify them in function_string . The smaller the step, the smoother your graph. - < function_string >
- Your function, written in the muParser syntax . The function is applied to the variables and data specified in variable_data . You can only reference the variables declared in this local function set, not in another piped set of
chfd
parameters. Summary muParser functions are not supported (min, max sum, avg). IMPORTANT: Remember to use%2B
instead of+
in your functions!
Examples
Описание | Пример |
---|---|
A simple sine wave. Some things to notice:
| cht=lc |
This line uses data from the chd parameter. | chd=t:5,10 |
A mix of function and non-function lines. Notice how the colors are specified by the series color parameter Notice the placement of markers on the function output; the data points are calculated from start , end , and step , so if your range is 0—11 step 0.1, point 0 is 0, point 1 is 0.1 and so on, until point 110, which has a value of 11. | chd=t: |
To define a function in two dimensions, use an
| cht=lxy |
The Try clicking these images to open and play with them in the chart playground; you'll get hooked! |
This document describes how to create pie charts using the Chart API.
Table of Contents
Chart-Specific Features
| Standard Features
|
Обзор
Pie charts are good for showing simple proportional part-to-whole information. You can create a single series pie chart, where each series is made of multiple slices, or multi-series, concentric charts.
Each series describes one pie, and each data value specifies one slice. When using nested pie charts (described below), use multiple series.
To display the text associated with a slice, you will have to use either pie chart labels or a chart legend . Pie chart labels are text around the chart with lines pointing toward the slice. Legends are text associated by color.
Labels | Легенда | Labels and Legend |
---|---|---|
chl=January|February|March|April | chdl=January|February|March|April | chl=January|February|March|April |
Values are displayed relative to each other: so a chart with values 1,2,3 will look the same as a chart with values 100,200,300. However, when using text format data, values greater than 100 are trimmed to 100, so you will need to use text format with custom scaling to display slices greater than 100 properly (use the chds
parameter with min/max values of chds=0,< max-slice-size >
).
Negative values display as empty slices of the appropriate size.
Chart Types
There are three general types of pie charts that you can create: flat, concentric, or 3D. Specify a pie chart with the following syntax:
Syntax
cht=<chart_type>
Where < chart_type >
is one of the the following types:
Parameter | Описание | Пример |
---|---|---|
| Two dimensional pie chart. Supply one data series only; subsequent data series are ignored. By default, pie segment colors are interpolated from dark orange to pale yellow. Specify other colors as described in Series Colors . Specify labels with The Google Chart API calculates the circle's radius from the minimum of width and height specified in the chart size ( | |
| A three-dimensional pie chart. Specify data and formatting in the same way as for two dimensional pie charts, above. If you are including labels in a three-dimensional pie chart, you probably need to specify the size of the width to be 2.5 times the size of the height, to ensure that your labels are fully visible. | |
| A concentric pie chart. Supply two or more data series. | |
All types | Negative numbers in data cause "blank" slices. | cht=pc |
Series Colors chco
You can specify the colors of all values, each value, or some values using the chco
parameter.
Syntax
chco=<slice_1>|<slice_2>|<slice_n>,<series_color_1>,...,<series_color_n>
- < color >
- Slice colors in RRGGBB hexadecimal format . Specify a single series color and all slices in that series will be colored in gradations of that color from darkest (first data member) to lightest (last data member). Specify two or more colors delimited by a | to describe individual slice colors. When you have multiple series (that is, a chart with concentric rings), you can specify values for different series by separating values by a comma. When fewer slice/series colors are given than slices/series displayed, then the chart will cycle through from the beginning of the slice list for the series, or the series list for the chart. You cannot specify a distinct gradient for each series in a multi-series chart.
Описание | Пример |
---|---|
Specify a single color to have gradations from darkest (first slice) to lightest (last slice). | |
Defining a gradient; here, from yellow to red. |
|
Defining individual slice colors; specify one color per slice. | chd=t:10,20,30 |
This chart has two data series, but specifies color as a single gradient across all slices from yellow to red (BBBB00—BB0000). | chco=BBBB00,BB0000 |
Here's a concentric chart that includes both series colors and individual slice colors. The chart has two concentric data series. In human-readable form, the colors are chco=green|red,blue|yellow. The comma breaks this into two series:
| chd=s:eYY,ORVM |
Pie Chart Labels chl
You can specify labels for individual pie chart slices using the chl
parameter. You can also display a legend with the same or different values, one legend entry per slice.
A Note on String Values: Only URL-safe characters are permitted in label strings. To be safe, you should URL-encode any strings containing characters not in the character set 0-9a-zA-Z
. You can find a URL encoder here .
Syntax
chl= <label_value>| ... <label_value>
- <label_value >
- A string value to apply to a slice. Labels are applied consecutively to the data points in
chd
. If you have multiple series (for a concentric pie chart, for example), labels are applied to all points in all sequences, in the order specified inchd
. Use a pipe delimiter (|
) between each label. Specify a missing intervening value by using two consecutive pipe characters with no space between them:||
. You do not need to label all slices.
Examples
Описание | Пример |
---|---|
Labels for a three-dimensional pie chart. | |
When specifying the size of your chart with Generally, a two-dimensional pie chart needs to be approximately twice as wide as it is high, and a three-dimensional pie chart needs to be approximately two and a half times wider than it is high, to display labels properly. In the first example, the labels are only partially displayed, because the chart is not wide enough. The second example shows that the chart needs a width of 280 pixels to display the labels in full. (Borders added explicitly to the | |
Pie Chart Rotation chp
By default, the first series is drawn starting at 3:00, continuing clockwise around the chart, but you can specify a custom rotation using the chp
parameter.
Syntax
chp=<radians>
- <radians >
- A floating point value describing how many radians to rotate the chart clockwise. One complete turn is 2 π (2 pi—about 6.28) radians.
Examples
Описание | Пример |
---|---|
To change the orientation of a pie chart, use | |
Here's another example of pie chart rotations. These can be combined with chart shape markers to create some interesting effects . |
Standard Features
The rest of the features on this page are standard chart features.
Chart Title chtt
, chts
[ All charts ]
You can specify the title text, color, and font size for your chart.
Syntax
chtt=<chart_title> chts=<color>,<font_size>,<opt_alignment>
chtt
- Specifies the chart title.
- < chart_title >
- Title to show for the chart. You cannot specify where this appears, but you can optionally specify the font size and color. Use a + sign to indicate spaces, and a pipe character (
|
) to indicate line breaks.
chts
[ Optional ] - Colors and font size for the chtt
parameter.
- <color >
- The title color, in RRGGBB hexadecimal format . Default color is black.
- <font_size >
- Font size of the title, in points.
- < opt_alignment >
- [ Optional ] Alignment of the title. Choose one of the following case-sensitive string values: "l" (left), "c" (centered) "r" (right). Default is "c".
Examples
Описание | Пример |
---|---|
A chart with a title, using default color and font size. Specify a space with a plus sign ( Use a pipe character ( | chtt=Site+visitors+by+month| |
A chart with a blue, right-aligned, 20-point title. | chtt=Site+visitors |
Chart Legend Text and Style chdl
, chdlp
, chdls
[ All charts ]
The legend is a side section of the chart that gives a small text description of each series. You can specify the text associated with each series in this legend, and specify where on the chart it should appear.
See also chma
, to learn how to set the margins around your legend.
A note on string values: Only URL-safe characters are permitted in label strings. To be safe, you should URL-encode any strings containing characters not in the character set 0-9a-zA-Z
. You can find a URL encoder in the Google Visualization Documentation .
Syntax
chdl=<data_series_1_label>|...|<data_series_n_label> chdlp=<opt_position>|<opt_label_order> chdls=<color>,<size>
chdl
- The text for each series, to display in the legend.
- < data_series_label >
- The text for the legend entries. Each label applies to the corresponding series in the
chd
array. Use a + mark for a space. If you do not specify this parameter, the chart will not get a legend. There is no way to specify a line break in a label. The legend will typically expand to hold your legend text, and the chart area will shrink to accommodate the legend.
chdlp
- [ Optional ] The position of the legend, and order of the legend entries. You can specify < position > and/or < label_order >. If you specify both, separate them with a bar character. You can add an 's' to any value if you want empty legend entries in chdl
to be skipped in the legend. Examples: chdlp=bv
, chdlp=r
, chdlp=bv|r
, chdlp=bvs|r
- < opt_position >
- [ Optional ] Specifies the position of the legend on the chart. To specify additional padding between the legend and the chart area or the image border, use the
chma
parameter. Choose one of the following values:-
b
- Legend at the bottom of the chart, legend entries in a horizontal row. -
bv
- Legend at the bottom of the chart, legend entries in a vertical column. -
t
- Legend at the top of the chart, legend entries in a horizontal row. -
tv
- Legend at the top of the chart, legend entries in a vertical column. -
r
- [ Default ] Legend to the right of the chart, legend entries in a vertical column. -
l
- Legend to the left of the chart, legend entries in a vertical column.
-
- < opt_label_order >
- [ Optional ] The order in which the labels are shown in the legend. Choose one of the following value:
-
l
- [ Default for vertical legends ] Display labels in the order given tochdl
. -
r
- Display labels in the reverse order as given tochdl
. This is useful in stacked bar charts to show the legend
in the same order as the bars appear. -
a
- [ Default for horizontal legends ] Automatic ordering: roughly means sorting by length, shortest first, as measured in 10 pixel blocks. When two elements are the same length (divided into 10 pixel blocks), the one listed first will appear first. -
0,1,2...
- Custom label order. This is a list of zero-based label indexes fromchdl
, separated by commas.
-
chdls
- [ Optional ] Specifies the color and font size of the legend text.
- < color >
- The legend text color, in RRGGBB hexadecimal format .
- < size >
- The point size of the legend text.
Examples
Описание | Пример |
---|---|
Two examples of legends. Specify legend text in the same order as your data series. | chdl=NASDAQ|FTSE100|DOW chdl=First|Second|Third |
The first chart demonstrates horizontal legend entries ( | |
This example demonstrates changing the font size. | |
Chart Margins chma
[ All charts ]
You can specify the size of the chart's margins, in pixels. Margins are calculated inward from the specified chart size ( chs
); increasing the margin size does not increase the total chart size, but rather shrinks the chart area, if necessary.
The margins are by default whatever is left over after the chart size is calculated. This default value varies by chart type. The margins that you specify are a minimum value; if the chart area leaves room for margins, the margin size will be whatever is left over; you cannot squeeze the margins smaller than what is required for any legends and labels. Here's a diagram showing the basic parts of a chart:
The chart margins include the axis labels and the legend area . The legend area resizes automatically to fit the text exactly, unless you specify a larger width using Tip: In a bar chart, if the bars have a fixed size (the default), the chart area width cannot be reduced. You must specify a smaller or resizeable bar size using |
Syntax
chma= <left_margin>,<right_margin>,<top_margin>,<bottom_margin>|<opt_legend_width>,<opt_legend_height>
- < left_margin >, < right_margin >, < top_margin >, < bottom_margin >
- Minimum margin size around the chart area, in pixels. Increase this value to include some padding to prevent axis labels from bumping against the borders of the chart.
- < opt_legend_width >, < opt_legend_height >
- [ Optional ] Width of the margin around the legend, in pixels. Use this to avoid having the legend bump up against the chart area or the edges of the image.
Examples
Описание | Пример |
---|---|
In this example, the chart has a minimum margin of 30 pixels on each side. Because the chart legend is more than 30 pixels wide, the margin on the right side is set to the width of the chart legend, and is different from the other margins. Axis labels are outside the plot area, and are therefore drawn within the margin space. |
|
To add a margin around the legend, set a value for the In this example, the legend is approximately 60 pixels wide. If you set the the |
|
Axis Styles and Labels [ Line, Bar, Google-o-meter, Radar, Scatter ]
You can specify which axes to display on the chart, and give them custom labels and positions, ranges, and styles.
Not all charts show axis lines by default. You can specify exactly which axes your chart should show using the chxt
parameter. Default axis lines do not show numbers; you must specify an axis in the chxt
parameter to show numbers.
You can choose to have your axes display numbers reflecting the data values, or you can specify custom axes. The default is to display numeric values, with values scaled to range from 0—100. However, you can change that range using chxr
to display any range, and you can style the values (for example, to show currency symbols or decimal places) using chxs
.
If you choose to use custom values, for example: "Mon, Tues, Wed", you can use the chxl
parameter. To place these labels in specific locations along the axis, use the chxp
parameter.
Finally, you can use the chxs
and chxtc
parameters to specify color, size, alignment, and other properties of both custom and numeric axis labels.
A note on string values: Only URL-safe characters are permitted in label strings. To be safe, you should URL-encode any strings containing characters not in the character set 0-9a-zA-Z
. You can find a URL encoder in the Google Visualization Documentation .
This section covers the following topics:
- Visible Axes (
chxt
) - Which axes to display. - Axis range (
chxr
) - Value range for each axis. - Custom Axis Labels (
chxl
) - Custom values to show on the axis. - Axis label positions (
chxp
) - Placement of custom labels along each axis. - Axis label styles (
chxs
) - Color, size, alignment, and formatting of axis labels. - Axis tick mark styles (
chxtc
) - Length of tick marks for a specific axis.
Visible Axes chxt
Bar, line, radar, and scatter charts show one or two axis lines by default, but these lines do not include values. To display values on your axis lines, or to change which axes are shown, you must use the chxt
parameter. By default, the axis values range from 0-100, unless you scale them explicitly using the chxr
property. To hide all axis lines in a line chart, specify :nda
after the chart type value in the cht
parameter (example: cht= lc:nda
).
By default, the top and bottom axes do not show tick marks by the values, while the left and right axes do show them. You can change this behavior using the chxs
parameter.
Syntax
chxt= <axis_1> ,..., <axis_n>
- < axis >
- An axis to show on the chart. Available axes are:
-
x
- Bottom x-axis -
t
- Top x-axis [ Not supported by Google-o-Meter ] -
y
- Left y-axis -
r
- Right y-axis [ Not supported by Google-o-Meter ]
-
You can specify multiple axes of the same type, for example: cht=x,x,y
. This will stack two sets of x-axes along the bottom of the chart. This is useful when adding custom labels along an axis that shows numeric values (see the example below). Axes are drawn from the inside out, so if you have x,x
, the first x refers to the innermost copy, the next x refers to the next outwards copy, and so on.
Examples
Описание | Пример |
---|---|
This example shows a line chart with an x-axis, a y-axis, a top axis (t), and a right axis (r). Because no labels are specified, the chart defaults to a range of 0 to 100 for all axes. Note that by default, the top and bottom axes don't show tick marks by the labels. |
|
You can include multiple sets of labels for each axis by including the same value more than once. This example shows two sets of x and two sets of y-axes. This isn't particularly useful when using only the default axis labels, as is shown here. But you can specify custom labels for each copy of each axis, using the chxl parameter. | chxt=x,x,y,y chxt=x,x,y,y |
This example shows a horizontal bar chart with an x-axis, a y-axis, an upper t-axis, and a right r-axis. Axis labels are omitted, so the Chart API displays a range of 0 to 100 for the x-axis and for the t-axis. The range for the y-axis and for the r-axis is determined by the number of bars. In this case, there are five bars, so the Chart API displays a range of 0 to 4. The first label is centered at the base of the first bar, the second label is centered at the base of the second bar, and so on. |
|
You can suppress default axes in a line chart by specifying :nda after the chart type. | cht=lc:nda |
Axis Range chxr
You can specify the range of values that appear on each axis independently, using the chxr parameter. Note that this does not change the scale of the chart elements, only the scale of the axis labels. If you want to make the axis numbers describe the actual data values, set < start_val > and < end_val > to the lower and upper values of your data format range, respectively. See Axis Scaling for more information.
You must make an axis visible using the chxt
parameter if you want to specify its range.
To specify custom axis values, use the chxl
parameter.
Syntax
Separate multiple axis label ranges using the pipe character ( |
).
chxr= <axis_index>,<start_val>,<end_val>,<opt_step> |...| <axis_index>,<start_val>,<end_val>,<opt_step>
- <axis_index >
- Which axis to apply the labels to. This is a zero-based index into the axis array specified by
chxt
. For example, the r-axis would be 1 inchxt=x,r,y
. - < start_val >
- A number, defining the low value for this axis.
- < end_val >
- A number, defining the high value for this axis.
- < opt_step >
- [ Optional ] The count step between ticks on the axis. There is no default step value; the step is calculated to try to show a set of nicely spaced labels.
Examples
Описание | Пример |
---|---|
This example shows left and right y-axes ( Each axis has a defined range. Because no labels or positions are specified, values are taken from the given range, and are evenly spaced within that range. In the line chart, values are evenly spread along the x-axis. Axis direction is reversed for the r-axis (index |
|
In this example, values are specified for the x-axis. Axis labels are evenly spaced along the axis. A value of five ( | |
Custom Axis Labels chxl
You can specify custom string axis labels on any axis, using the chxl
parameter. You can specify as many labels as you like. If you display an axis (using the chxt
parameter) and do not specify custom labels, the standard, numeric labels will be applied. To specify a custom numeric range, use the chxr
parameter instead.
To set specific locations along the axis for your labels, use the chxp
parameter.
Syntax
Specify one parameter set for each axis that you want to label. Separate multiple sets of labels using the pipe character ( |
).
chxl= <axis_index>:|<label_1>|...|<label_n> |...| <axis_index>:|<label_1>|...|<label_n>
- <axis_index >
- Which axis to apply labels to. This is an index into the
chxt
parameter array. For example, if you havechxt=x,x,y,y
then index 0 would be the first x-axis, 1 would be the second x-axis. - <label_1> | ... |< label_n >
- One or more labels to place along this axis. These can be string or number values; strings do not need to be in quotes. label_1 is displayed at the lowest position on the axis, and label_n is displayed at the highest position. Additional labels are spaced evenly between them. Indicate spaces with a + mark. There is no way to specify a line break in a label. Separate labels with a pipe character. Note: Do not place a pipe after the final label in the
chxl
parameter.
Examples
Описание | Пример |
---|---|
This chart shows how to add custom labels to two axes. Note how the values are evenly spaced, and how the last | chxt=x,y |
This example includes axis labels on the left and right y-axes ( |
|
This example includes axis labels on the left and right y-axes ( This example uses default values for the axis labels on the left y-axis. |
|
If you want to add a generic label to describe a whole axis (for example, to label one axis "cost" and another "student"), use the | chxt=x,x,y,y |
Axis Label Positions chxp
You can specify which axis labels to show, whether using the default labels or custom labels specified using chxl
. If you do not specify exact positions using this parameter, labels will be spaced evenly and at a default step value along the axes. If you do not specify chxl
, then the tick mark labels will be the default values (typically data values, or the bar numbers in bar charts).
Syntax
Separate multiple positioning sets using the pipe character ( |
).
chxp= <axis_1_index>,<label_1_position>,...,<label_n_position> |...| <axis_m_index>,<label_1_position>,...,<label_n_position>
- <axis_index >
- The axis for which you are specifying positions. This is an index into the
chxt
parameter array. For example, if you havechxt=x,x,y,y
then index 0 would be the first x-axis, 1 would be the second x-axis, and so on. - < label_1_position >,...,< label_n_position >
- The position of the label along the axis. This is a comma-separated list of numeric values, where each value sets the position of the corresponding label in the
chxl
array: the first entry applies to the first label, and so on. The position is a value in the range for that axis . Note that this will always be 0—100 unless you have specified a custom range usingchxr
. You must have as many positions as you have labels for that axis.
Examples
Описание | Пример |
---|---|
This example includes r-axis labels at specified positions on the chart. The label text is specified using the Labels with a specified position of Labels with a specified position of | |
This example demonstrates showing the default label values, but only at specified locations. |
chxt=x,y chxt=x,y chxp not specified |
Axis Label Styles chxs
You can specify the font size, color, and alignment for axis labels, both custom labels and default label values. All labels on the same axis have the same format. If you have multiple copies of an axis, you can format each one differently. You can also specify the format of a label string, for example to show currency symbols or trailing zeroes.
By default, the top and bottom axes do not show tick marks by the values, while the left and right axes do show them.
Syntax
Values for multiple axes should be separated using a pipe character ( |
).
chxs= <axis_index><opt_format_string>,<opt_label_color>,<opt_font_size>,<opt_alignment>,<opt_axis_or_tick>,<opt_tick_color>,<opt_axis_color> |...| <axis_index><opt_format_string>,<opt_label_color>,<opt_font_size>,<opt_alignment>,<opt_axis_or_tick>,<opt_tick_color>,<opt_axis_color>
- < axis_index >
- The axis to which this applies. This is a zero-based index into the
chxt
parameter. - < opt_format_string >
- [ Optional ] This is an optional format string that, if used, follows immediately after the axis index number without an intervening comma. It starts with a literal letter N followed by the following values, all optional:
N< preceding_text >*< number_type >< decimal_places >zs< x or y >*< following_text >
Here is the meaning of each element:-
<preceding_text>
- Literal text to precede each value. -
*...*
- An optional block wrapped in literal asterisks, in which you can specify formatting details for numbers. The following values are supported, and are all optional:-
<number_type>
- The number format, for numeric values. Choose one of the following:-
f
- [ Default ] Floating point format. Consider specifying precision as well with the < decimal_places > value. -
p
- Percentage format. A % sign is appended automatically. Note: When using this format, data values from 0.0 — 1.0 map to 0 — 100% (for example, 0.43 will be shown as 43%). -
e
- Scientific notation format. -
c< CUR >
- Format the number in the currency specified, with the appropriate currency marker. Replace< CUR >
with a three-letter currency code. Example:cEUR
for Euros. You can find a list of codes on the ISO web site , although not all symbols are supported.
-
-
<decimal_places>
- An integer specifying how many decimal places to show. The value is rounded (not truncated) to this length. Default is 2. -
z
- Display trailing zeros. Default is no . -
s
- Display group separators. Default is no . -
x
ory
-Display the data from the x- or y-coordinate, as specified. The meaning of x data varies by chart type: experiment with your chart to determine what it means. Default is 'y' .
-
-
< following_text >
- Literal text to follow each value.
-
- < opt_label_color >
- The color to apply to the axis text (but not axis line), in RRGGBB hexadecimal format . Axis line color is specified separately using opt_axis_color . Default is gray.
- < opt_font_size >
- [ Optional ] specifies the font size in pixels. This parameter is optional.
- < opt_alignment >
- [ Optional ] Label alignment. For top or bottom axes, this describes how the label aligns to the tick mark above or below it; for left or right axes, this describes how the aligns inside its bounding box, which touches the axis. Specify one of the following numbers:
-
-1
- Top or bottom : labels are to the right of the ticks; Left or right : labels are left-aligned in their area. Default for r-axis labels. -
0
- Top or bottom : labels are centered on the ticks; Left or right : labels are centered in their area. Default for x- and t-axis labels. -
1
- Top or bottom : labels are to the left of the ticks; Left or right : labels are right-aligned in their area. Default for y-axis labels.
-
- < opt_axis_or_tick >
- [ Optional; not supported in Google-o-meter ] Whether to show tick marks and/or axis lines for this axis. Tick marks and axis lines are only available for innermost axes (for example, they are not supported for the outer of two x-axes). Use one of the following values:
-
l
(lowercase 'L') - Draw axis line only. -
t
- Draw tick marks only. Tick marks are the little lines next to axis labels. -
lt
- [ Default ] Draw both an axis line and tick marks for all labels. -
_
- (Underscore) Draw neither axis line nor tick marks. If you want to hide an axis line, use this value.
-
- < tick_color >
- [ Optional ; not supported in Google-o-meter ] The tick mark color, in RRGGBB hexadecimal format . Default is gray.
- < opt_axis_color >
- [ Optional ] The color of this axis line, in RRGGBB hexadecimal format . Default is gray.
Examples
Описание | Пример |
---|---|
Font size and color are specified for the second x-axis (Jan, Feb, Mar). | |
Font size, color, and alignment are specified for the right y-axis. Tick marks, but no axis line, are drawn. | |
This chart includes three data sets, and shows three sets of axis labels, one per series. Each set of labels is formatted using a custom formatting string, as described here:
The axis label ranges are set using the | chd=s: |
Axis Tick Mark Styles chxtc
You can specify long tick marks for specific axes. Typically this is used to extend a tick mark across the length of a chart. Use the chxs
parameter to change the tick mark color.
Values for multiple axes should be separated using a pipe character ( |
). Values within a series should be separated by a comma.
Syntax
chxtc= <axis_index_1>,<tick_length_1>,...,<tick_length_n> |...| <axis_index_m>,<tick_length_1>,...,<tick_length_n>
- < axis_index >
- The axis to which this applies. This is a zero-based index into the
chxt
parameter. Separate values for different axes using a bar delimiter. - < tick_length_1 >,...,< tick_length_n >
- Length of the tick marks on that axis, in pixels. If a single value is given, it will apply to all values; if more than one value is given, the axis tick marks will cycle through the list of values for that axis. Positive values are drawn outside the chart area and cropped by the chart borders. The maximum positive value is 25. Negative values are drawn inside the chart area and cropped by the chart area borders.
Examples
Описание | Пример |
---|---|
Example of using
| |
This chart demonstrates alternating tick lengths. chxtc specifies two tick length values for the y-axis (5 and 15), and the ticks drawn on the chart alternate between the two values. | chxt=x,y |
Background Fills chf
[ All charts ]
You can specify fill colors and styles for the chart data area and/or the whole chart background. Fill types include solid fills, striped fills, and gradients. You can specify different fills for different areas (for example, the whole chart area, or just the data area). The chart area fill overwrites the background fill. All fills are specified using the chf
parameter, and you can mix different fill types (solids, stripes, gradients) in the same chart by separating values with pipe character ( | ). Chart area fills overwrite chart background fills.
Solid Fills chf
[ All Charts ]
You can specify a solid fill for the background and/or chart area, or assign a transparency value to the whole chart. You can specify multiple fills using the pipe character ( |
). (Maps: background only).
Syntax
chf=<fill_type>,s,<color>|...
- < fill_type >
- The part of the chart being filled. Specify one of the following values:
-
bg
- Background fill -
c
- Chart area fill. Not supported for map charts. -
a
- Make the whole chart (including backgrounds) transparent. The first six digits of< color >
are ignored, and only the last two (the transparency value) are applied to the whole chart and all fills. -
b <index>
- Bar solid fills (bar charts only). Replace < index > with the series index of the bars to fill with a solid color. The effect is similar to specifyingchco
in a bar chart. See Bar Chart Series Colors for an example.
-
- с
- Indicates a solid or transparency fill.
- < color >
- The fill color, in RRGGBB hexadecimal format . For transparencies, the first six digits are ignored, but must be included anyway.
Examples
Описание | Пример |
---|---|
This example fills the chart background with pale gray ( | |
This example fills the chart background with pale gray ( | |
This example applies a 50% transparency to the whole chart (80 in hexadecimal is 128, or about 50% transparency). Notice the table cell background showing through the chart. | |
Gradient Fills chf
[ Line, Bar, Google-o-meter, Radar, Scatter,Venn ]
You can apply one or more gradient fills to chart areas or backgrounds. Gradient fills are fades from a one color to another color. (Pie, Google-o-meter charts: background only.)
Each gradient fill specifies an angle, and then two or more colors anchored to a specified location. The color varies as it moves from one anchor to another. You must have at least two colors with different < color_centerpoint > values, so that one can fade into the other. Each additional gradient is specified by a < color >,< color_centerpoint > pair.
Syntax
chf=<fill_type>,lg,<angle>,<color_1>,<color_centerpoint_1> ,..., <color_n>,<color_centerpoint_n>
- < fill_type >
- The chart area to fill. One of the following:
-
bg
- Background fill -
c
- Chart area fill. -
b <index>
- Bar gradient fills (bar charts only). Replace < index > with the series index of the bars to fill with a gradient. See Bar Chart Series Colors for an example.
-
- lg
- Specifies a gradient fill.
- < angle >
- A number specifying the angle of the gradient from 0 (horizontal) to 90 (vertical).
- < color >
- The color of the fill, in RRGGBB hexadecimal format .
- < color_centerpoint >
- Specifies the anchor point for the color. The color will start to fade from this point as it approaches another anchor. The value range is from 0.0 (bottom or left edge) to 1.0 (top or right edge), tilted at the angle specified by < angle >.
Examples
Описание | Пример |
---|---|
Chart area has a horizontal linear gradient, specified with an angle of zero degrees ( The colors are peach ( The chart background is drawn in gray ( | |
Chart area has a diagonal (bottom left to top right) linear gradient, specified with an angle of forty-five degrees ( Peach ( Blue ( The chart background is drawn in gray ( | |
Chart area has a vertical (top to bottom) linear gradient, specified with an angle of ninety degrees ( Blue ( Peach ( The chart background is drawn in gray ( | |
Striped fills chf
[ Line, Bar, Google-o-meter, Radar, Scatter, Venn ]
You can specify a striped background fill for your chart area, or the whole chart. (Pie, Google-o-meter charts: background only.)
Syntax
chf= <fill_type>,ls,<angle>,<color_1>,<width_1> ,..., <color_n>,<width_n>
- < fill_type >
- The chart area to fill. One of the following:
-
bg
- Background fill -
c
- Chart area fill -
b <index>
- Bar striped fills (bar charts only). Replace < index > with the series index of the bars to fill with stripes. See Bar Chart Series Colors for an example.
-
- ls
- Specifies linear stripe fill.
- < angle >
- The angle of all stripes, relative to the y-axis. Use
0
for vertical stripes or90
for horizontal stripes. - < color >
- The color for this stripe, in RRGGBB hexadecimal format . Repeat < color > and < width > for each additional stripe. You must have at least two stripes. Stripes alternate until the chart is filled.
- < width >
- The width of this stripe, from
0
to1
, where1
is the full width of the chart. Stripes are repeated until the chart is filled. Repeat < color > and < width > for each additional stripe. You must have at least two stripes. Stripes alternate until the chart is filled.
Examples
Описание | Пример |
---|---|
| chf= |
| chf= |
Data Functions chfd
[ All chd
charts ]
You can specify a custom function to run over chart data using muParser function syntax . The data used in the function can come from one of two sources:
- A data series from
chd
- The data is pulled from the specified series inchd
. - A range of values declared in the
chfd
parameter itself - You declare a start, stop, and step value for an arbitrary data range.
It is important to note that in all cases you must assign the output to an existing series in chd
; that series will be overwritten by the function output. The chart is rendered only after all functions have been processes, so if you assign multiple functions to output to the same data series, the functions will be run in the order given, but only the output of the final function will be plotted on the chart. Note that you can chain functions, so that one function can take as input a series that was output by a previous function.
To assign colors or chm
markers to a function line, assign the colors or markers to the function's series index. Note that markers are placed according to the data after it has been manipulated by the function.
Syntax
chfd= <output_series_index>,<function_data>,<function_string> |...| <output_series_index>,<function_data>,<function_string>
- < output_series_index >
- Zero-based index of a data series in
chd
to which the function output will be written. Any existing data will be completely overwritten by the function output. If a series is not being used as input for a function, best practice is to assign a single dummy value to that series. - < function_data >
- The variables and data to plot. The data can be from a range that you define, or from one of the
chd
data series. You can specify multiple variables for each function, using a ; (semicolon) delimiter for multiple variables. Note that if you define multiple variables for a single function, and these variables have a different number of points, the function will stop when it reaches the first endpoint. For example, if a function defines both x=1—5 step 1 and y=1—10 step 1, the function will end when it reaches the fifth point.
< variable_name >,< input_series_index >
OR
< variable_name >,< start >,< end >,< step >
- variable_name - An arbitrary string name for the variable. Use this in the function defined by function_string .
- input_series_index - The index of a
chd
data series to use as input data. - start - The numeric start value of a range.
- end - The numeric end value of a range.
- step - The numeric step value from start to end . Can be positive or negative, but cannot be zero.
x,0,100,1
declares a variable namedx
with values 0, 1, 2, ... 100.x,0,100,1;r,0,3.1,.1
declares the samex
variable plus a variable namedr
with values 0, 0.1, 0.2, ..., 3.0, 3.1.x,0
declares a variable named x that uses the data from the firstchd
series. These variables will be used by function_string . They will not be plotted on the graph unless you specify them in function_string . The smaller the step, the smoother your graph. - < function_string >
- Your function, written in the muParser syntax . The function is applied to the variables and data specified in variable_data . You can only reference the variables declared in this local function set, not in another piped set of
chfd
parameters. Summary muParser functions are not supported (min, max sum, avg). IMPORTANT: Remember to use%2B
instead of+
in your functions!
Examples
Описание | Пример |
---|---|
A simple sine wave. Some things to notice:
| cht=lc |
This line uses data from the chd parameter. | chd=t:5,10 |
A mix of function and non-function lines. Notice how the colors are specified by the series color parameter Notice the placement of markers on the function output; the data points are calculated from start , end , and step , so if your range is 0—11 step 0.1, point 0 is 0, point 1 is 0.1 and so on, until point 110, which has a value of 11. | chd=t: |
To define a function in two dimensions, use an
| cht=lxy |
The Try clicking these images to open and play with them in the chart playground; you'll get hooked! |