pygooglechart-0.3.0/000755 000766 000024 00000000000 11421530342 014262 5ustar00gakstaff000000 000000 pygooglechart-0.3.0/COPYING000644 000766 000024 00000077331 11421527536 015343 0ustar00gakstaff000000 000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS pygooglechart-0.3.0/examples/000755 000766 000024 00000000000 11421530342 016100 5ustar00gakstaff000000 000000 pygooglechart-0.3.0/MANIFEST.in000644 000766 000024 00000000061 11421527536 016030 0ustar00gakstaff000000 000000 recursive-include examples *.py include COPYING pygooglechart-0.3.0/PKG-INFO000644 000766 000024 00000001362 11421530342 015361 0ustar00gakstaff000000 000000 Metadata-Version: 1.0 Name: pygooglechart Version: 0.3.0 Summary: A complete Python wrapper for the Google Chart API Home-page: http://pygooglechart.slowchop.com/ Author: Gerald Kaszuba Author-email: gerald@geraldkaszuba.com License: UNKNOWN Download-URL: http://pygooglechart.slowchop.com/files/download/pygooglechart-0.3.0.tar.gz Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Scientific/Engineering :: Visualization Classifier: Topic :: Software Development :: Libraries :: Python Modules pygooglechart-0.3.0/pygooglechart.egg-info/000755 000766 000024 00000000000 11421530342 020623 5ustar00gakstaff000000 000000 pygooglechart-0.3.0/pygooglechart.py000644 000766 000024 00000112515 11421527536 017523 0ustar00gakstaff000000 000000 """ pygooglechart - A complete Python wrapper for the Google Chart API http://pygooglechart.slowchop.com/ Copyright 2007-2009 Gerald Kaszuba This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ from __future__ import division import os import urllib import urllib2 import math import random import re import warnings import copy # Helper variables and functions # ----------------------------------------------------------------------------- __version__ = '0.3.0' __author__ = 'Gerald Kaszuba' reo_colour = re.compile('^([A-Fa-f0-9]{2,2}){3,4}$') def _check_colour(colour): if not reo_colour.match(colour): raise InvalidParametersException('Colours need to be in ' \ 'RRGGBB or RRGGBBAA format. One of your colours has %s' % \ colour) def _reset_warnings(): """Helper function to reset all warnings. Used by the unit tests.""" globals()['__warningregistry__'] = None # Exception Classes # ----------------------------------------------------------------------------- class PyGoogleChartException(Exception): pass class DataOutOfRangeException(PyGoogleChartException): pass class UnknownDataTypeException(PyGoogleChartException): pass class NoDataGivenException(PyGoogleChartException): pass class InvalidParametersException(PyGoogleChartException): pass class BadContentTypeException(PyGoogleChartException): pass class AbstractClassException(PyGoogleChartException): pass class UnknownChartType(PyGoogleChartException): pass class UnknownCountryCodeException(PyGoogleChartException): pass # Data Classes # ----------------------------------------------------------------------------- class Data(object): def __init__(self, data): if type(self) == Data: raise AbstractClassException('This is an abstract class') self.data = data @classmethod def float_scale_value(cls, value, range): lower, upper = range assert(upper > lower) scaled = (value - lower) * (cls.max_value / (upper - lower)) return scaled @classmethod def clip_value(cls, value): return max(0, min(value, cls.max_value)) @classmethod def int_scale_value(cls, value, range): return int(round(cls.float_scale_value(value, range))) @classmethod def scale_value(cls, value, range): scaled = cls.int_scale_value(value, range) clipped = cls.clip_value(scaled) Data.check_clip(scaled, clipped) return clipped @staticmethod def check_clip(scaled, clipped): if clipped != scaled: warnings.warn('One or more of of your data points has been ' 'clipped because it is out of range.') class SimpleData(Data): max_value = 61 enc_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' def __repr__(self): encoded_data = [] for data in self.data: sub_data = [] for value in data: if value is None: sub_data.append('_') elif value >= 0 and value <= self.max_value: sub_data.append(SimpleData.enc_map[value]) else: raise DataOutOfRangeException('cannot encode value: %d' % value) encoded_data.append(''.join(sub_data)) return 'chd=s:' + ','.join(encoded_data) class TextData(Data): max_value = 100 def __repr__(self): encoded_data = [] for data in self.data: sub_data = [] for value in data: if value is None: sub_data.append(-1) elif value >= 0 and value <= self.max_value: sub_data.append("%.1f" % float(value)) else: raise DataOutOfRangeException() encoded_data.append(','.join(sub_data)) return 'chd=t:' + '%7c'.join(encoded_data) @classmethod def scale_value(cls, value, range): # use float values instead of integers because we don't need an encode # map index scaled = cls.float_scale_value(value, range) clipped = cls.clip_value(scaled) Data.check_clip(scaled, clipped) return clipped class ExtendedData(Data): max_value = 4095 enc_map = \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.' def __repr__(self): encoded_data = [] enc_size = len(ExtendedData.enc_map) for data in self.data: sub_data = [] for value in data: if value is None: sub_data.append('__') elif value >= 0 and value <= self.max_value: first, second = divmod(int(value), enc_size) sub_data.append('%s%s' % ( ExtendedData.enc_map[first], ExtendedData.enc_map[second])) else: raise DataOutOfRangeException( \ 'Item #%i "%s" is out of range' % (data.index(value), \ value)) encoded_data.append(''.join(sub_data)) return 'chd=e:' + ','.join(encoded_data) # Axis Classes # ----------------------------------------------------------------------------- class Axis(object): BOTTOM = 'x' TOP = 't' LEFT = 'y' RIGHT = 'r' TYPES = (BOTTOM, TOP, LEFT, RIGHT) def __init__(self, axis_index, axis_type, **kw): assert(axis_type in Axis.TYPES) self.has_style = False self.axis_index = axis_index self.axis_type = axis_type self.positions = None def set_index(self, axis_index): self.axis_index = axis_index def set_positions(self, positions): self.positions = positions def set_style(self, colour, font_size=None, alignment=None): _check_colour(colour) self.colour = colour self.font_size = font_size self.alignment = alignment self.has_style = True def style_to_url(self): bits = [] bits.append(str(self.axis_index)) bits.append(self.colour) if self.font_size is not None: bits.append(str(self.font_size)) if self.alignment is not None: bits.append(str(self.alignment)) return ','.join(bits) def positions_to_url(self): bits = [] bits.append(str(self.axis_index)) bits += [str(a) for a in self.positions] return ','.join(bits) class LabelAxis(Axis): def __init__(self, axis_index, axis_type, values, **kwargs): Axis.__init__(self, axis_index, axis_type, **kwargs) self.values = [str(a) for a in values] def __repr__(self): return '%i:%%7c%s' % (self.axis_index, '%7c'.join(self.values)) class RangeAxis(Axis): def __init__(self, axis_index, axis_type, low, high, **kwargs): Axis.__init__(self, axis_index, axis_type, **kwargs) self.low = low self.high = high def __repr__(self): return '%i,%s,%s' % (self.axis_index, self.low, self.high) # Chart Classes # ----------------------------------------------------------------------------- class Chart(object): """Abstract class for all chart types. width are height specify the dimensions of the image. title sets the title of the chart. legend requires a list that corresponds to datasets. """ BASE_URL = 'http://chart.apis.google.com/chart?' BACKGROUND = 'bg' CHART = 'c' ALPHA = 'a' VALID_SOLID_FILL_TYPES = (BACKGROUND, CHART, ALPHA) SOLID = 's' LINEAR_GRADIENT = 'lg' LINEAR_STRIPES = 'ls' def __init__(self, width, height, title=None, legend=None, colours=None, auto_scale=True, x_range=None, y_range=None, colours_within_series=None): if type(self) == Chart: raise AbstractClassException('This is an abstract class') assert(isinstance(width, int)) assert(isinstance(height, int)) self.width = width self.height = height self.data = [] self.set_title(title) self.set_title_style(None, None) self.set_legend(legend) self.set_legend_position(None) self.set_colours(colours) self.set_colours_within_series(colours_within_series) # Data for scaling. self.auto_scale = auto_scale # Whether to automatically scale data self.x_range = x_range # (min, max) x-axis range for scaling self.y_range = y_range # (min, max) y-axis range for scaling self.scaled_data_class = None self.scaled_x_range = None self.scaled_y_range = None self.fill_types = { Chart.BACKGROUND: None, Chart.CHART: None, Chart.ALPHA: None, } self.fill_area = { Chart.BACKGROUND: None, Chart.CHART: None, Chart.ALPHA: None, } self.axis = [] self.markers = [] self.line_styles = {} self.grid = None self.title_colour = None self.title_font_size = None # URL generation # ------------------------------------------------------------------------- def get_url(self, data_class=None): url_bits = self.get_url_bits(data_class=data_class) return self.BASE_URL + '&'.join(url_bits) def get_url_bits(self, data_class=None): url_bits = [] # required arguments url_bits.append(self.type_to_url()) url_bits.append('chs=%ix%i' % (self.width, self.height)) url_bits.append(self.data_to_url(data_class=data_class)) # optional arguments if self.title: url_bits.append('chtt=%s' % self.title) if self.title_colour and self.title_font_size: url_bits.append('chts=%s,%s' % (self.title_colour, \ self.title_font_size)) if self.legend: url_bits.append('chdl=%s' % '%7c'.join(self.legend)) if self.legend_position: url_bits.append('chdlp=%s' % (self.legend_position)) if self.colours: url_bits.append('chco=%s' % ','.join(self.colours)) if self.colours_within_series: url_bits.append('chco=%s' % '%7c'.join(self.colours_within_series)) ret = self.fill_to_url() if ret: url_bits.append(ret) ret = self.axis_to_url() if ret: url_bits.append(ret) if self.markers: url_bits.append(self.markers_to_url()) if self.line_styles: style = [] for index in xrange(max(self.line_styles) + 1): if index in self.line_styles: values = self.line_styles[index] else: values = ('1', ) style.append(','.join(values)) url_bits.append('chls=%s' % '%7c'.join(style)) if self.grid: url_bits.append('chg=%s' % self.grid) return url_bits # Downloading # ------------------------------------------------------------------------- def download(self, file_name): opener = urllib2.urlopen(self.get_url()) if opener.headers['content-type'] != 'image/png': raise BadContentTypeException('Server responded with a ' \ 'content-type of %s' % opener.headers['content-type']) open(file_name, 'wb').write(opener.read()) # Simple settings # ------------------------------------------------------------------------- def set_title(self, title): if title: self.title = urllib.quote(title) else: self.title = None def set_title_style(self, colour=None, font_size=None): if not colour is None: _check_colour(colour) if not colour and not font_size: return self.title_colour = colour or '333333' self.title_font_size = font_size or 13.5 def set_legend(self, legend): """legend needs to be a list, tuple or None""" assert(isinstance(legend, list) or isinstance(legend, tuple) or legend is None) if legend: self.legend = [urllib.quote(a) for a in legend] else: self.legend = None def set_legend_position(self, legend_position): if legend_position: self.legend_position = urllib.quote(legend_position) else: self.legend_position = None # Chart colours # ------------------------------------------------------------------------- def set_colours(self, colours): # colours needs to be a list, tuple or None assert(isinstance(colours, list) or isinstance(colours, tuple) or colours is None) # make sure the colours are in the right format if colours: for col in colours: _check_colour(col) self.colours = colours def set_colours_within_series(self, colours): # colours needs to be a list, tuple or None assert(isinstance(colours, list) or isinstance(colours, tuple) or colours is None) # make sure the colours are in the right format if colours: for col in colours: _check_colour(col) self.colours_within_series = colours # Background/Chart colours # ------------------------------------------------------------------------- def fill_solid(self, area, colour): assert(area in Chart.VALID_SOLID_FILL_TYPES) _check_colour(colour) self.fill_area[area] = colour self.fill_types[area] = Chart.SOLID def _check_fill_linear(self, angle, *args): assert(isinstance(args, list) or isinstance(args, tuple)) assert(angle >= 0 and angle <= 90) assert(len(args) % 2 == 0) args = list(args) # args is probably a tuple and we need to mutate for a in xrange(int(len(args) / 2)): col = args[a * 2] offset = args[a * 2 + 1] _check_colour(col) assert(offset >= 0 and offset <= 1) args[a * 2 + 1] = str(args[a * 2 + 1]) return args def fill_linear_gradient(self, area, angle, *args): assert(area in Chart.VALID_SOLID_FILL_TYPES) args = self._check_fill_linear(angle, *args) self.fill_types[area] = Chart.LINEAR_GRADIENT self.fill_area[area] = ','.join([str(angle)] + args) def fill_linear_stripes(self, area, angle, *args): assert(area in Chart.VALID_SOLID_FILL_TYPES) args = self._check_fill_linear(angle, *args) self.fill_types[area] = Chart.LINEAR_STRIPES self.fill_area[area] = ','.join([str(angle)] + args) def fill_to_url(self): areas = [] for area in (Chart.BACKGROUND, Chart.CHART, Chart.ALPHA): if self.fill_types[area]: areas.append('%s,%s,%s' % (area, self.fill_types[area], \ self.fill_area[area])) if areas: return 'chf=' + '%7c'.join(areas) # Data # ------------------------------------------------------------------------- def data_class_detection(self, data): """Determines the appropriate data encoding type to give satisfactory resolution (http://code.google.com/apis/chart/#chart_data). """ assert(isinstance(data, list) or isinstance(data, tuple)) if not isinstance(self, (LineChart, BarChart, ScatterChart)): # From the link above: # Simple encoding is suitable for all other types of chart # regardless of size. return SimpleData elif self.height < 100: # The link above indicates that line and bar charts less # than 300px in size can be suitably represented with the # simple encoding. I've found that this isn't sufficient, # e.g. examples/line-xy-circle.png. Let's try 100px. return SimpleData else: return ExtendedData def _filter_none(self, data): return [r for r in data if r is not None] def data_x_range(self): """Return a 2-tuple giving the minimum and maximum x-axis data range. """ try: lower = min([min(self._filter_none(s)) for type, s in self.annotated_data() if type == 'x']) upper = max([max(self._filter_none(s)) for type, s in self.annotated_data() if type == 'x']) return (lower, upper) except ValueError: return None # no x-axis datasets def data_y_range(self): """Return a 2-tuple giving the minimum and maximum y-axis data range. """ try: lower = min([min(self._filter_none(s)) for type, s in self.annotated_data() if type == 'y']) upper = max([max(self._filter_none(s)) + 1 for type, s in self.annotated_data() if type == 'y']) return (lower, upper) except ValueError: return None # no y-axis datasets def scaled_data(self, data_class, x_range=None, y_range=None): """Scale `self.data` as appropriate for the given data encoding (data_class) and return it. An optional `y_range` -- a 2-tuple (lower, upper) -- can be given to specify the y-axis bounds. If not given, the range is inferred from the data: (0, ) presuming no negative values, or (, ) if there are negative values. `self.scaled_y_range` is set to the actual lower and upper scaling range. Ditto for `x_range`. Note that some chart types don't have x-axis data. """ self.scaled_data_class = data_class # Determine the x-axis range for scaling. if x_range is None: x_range = self.data_x_range() if x_range and x_range[0] > 0: x_range = (x_range[0], x_range[1]) self.scaled_x_range = x_range # Determine the y-axis range for scaling. if y_range is None: y_range = self.data_y_range() if y_range and y_range[0] > 0: y_range = (y_range[0], y_range[1]) self.scaled_y_range = y_range scaled_data = [] for type, dataset in self.annotated_data(): if type == 'x': scale_range = x_range elif type == 'y': scale_range = y_range elif type == 'marker-size': scale_range = (0, max(dataset)) scaled_dataset = [] for v in dataset: if v is None: scaled_dataset.append(None) else: scaled_dataset.append( data_class.scale_value(v, scale_range)) scaled_data.append(scaled_dataset) return scaled_data def add_data(self, data): self.data.append(data) return len(self.data) - 1 # return the "index" of the data set def data_to_url(self, data_class=None): if not data_class: data_class = self.data_class_detection(self.data) if not issubclass(data_class, Data): raise UnknownDataTypeException() if self.auto_scale: data = self.scaled_data(data_class, self.x_range, self.y_range) else: data = self.data return repr(data_class(data)) def annotated_data(self): for dataset in self.data: yield ('x', dataset) # Axis Labels # ------------------------------------------------------------------------- def set_axis_labels(self, axis_type, values): assert(axis_type in Axis.TYPES) values = [urllib.quote(str(a)) for a in values] axis_index = len(self.axis) axis = LabelAxis(axis_index, axis_type, values) self.axis.append(axis) return axis_index def set_axis_range(self, axis_type, low, high): assert(axis_type in Axis.TYPES) axis_index = len(self.axis) axis = RangeAxis(axis_index, axis_type, low, high) self.axis.append(axis) return axis_index def set_axis_positions(self, axis_index, positions): try: self.axis[axis_index].set_positions(positions) except IndexError: raise InvalidParametersException('Axis index %i has not been ' \ 'created' % axis) def set_axis_style(self, axis_index, colour, font_size=None, \ alignment=None): try: self.axis[axis_index].set_style(colour, font_size, alignment) except IndexError: raise InvalidParametersException('Axis index %i has not been ' \ 'created' % axis) def axis_to_url(self): available_axis = [] label_axis = [] range_axis = [] positions = [] styles = [] index = -1 for axis in self.axis: available_axis.append(axis.axis_type) if isinstance(axis, RangeAxis): range_axis.append(repr(axis)) if isinstance(axis, LabelAxis): label_axis.append(repr(axis)) if axis.positions: positions.append(axis.positions_to_url()) if axis.has_style: styles.append(axis.style_to_url()) if not available_axis: return url_bits = [] url_bits.append('chxt=%s' % ','.join(available_axis)) if label_axis: url_bits.append('chxl=%s' % '%7c'.join(label_axis)) if range_axis: url_bits.append('chxr=%s' % '%7c'.join(range_axis)) if positions: url_bits.append('chxp=%s' % '%7c'.join(positions)) if styles: url_bits.append('chxs=%s' % '%7c'.join(styles)) return '&'.join(url_bits) # Markers, Ranges and Fill area (chm) # ------------------------------------------------------------------------- def markers_to_url(self): return 'chm=%s' % '%7c'.join([','.join(a) for a in self.markers]) def add_marker(self, index, point, marker_type, colour, size, priority=0): self.markers.append((marker_type, colour, str(index), str(point), \ str(size), str(priority))) def add_horizontal_range(self, colour, start, stop): self.markers.append(('r', colour, '0', str(start), str(stop))) def add_data_line(self, colour, data_set, size, priority=0): self.markers.append(('D', colour, str(data_set), '0', str(size), \ str(priority))) def add_marker_text(self, string, colour, data_set, data_point, size, \ priority=0): self.markers.append((str(string), colour, str(data_set), \ str(data_point), str(size), str(priority))) def add_vertical_range(self, colour, start, stop): self.markers.append(('R', colour, '0', str(start), str(stop))) def add_fill_range(self, colour, index_start, index_end): self.markers.append(('b', colour, str(index_start), str(index_end), \ '1')) def add_fill_simple(self, colour): self.markers.append(('B', colour, '1', '1', '1')) # Line styles # ------------------------------------------------------------------------- def set_line_style(self, index, thickness=1, line_segment=None, \ blank_segment=None): value = [] value.append(str(thickness)) if line_segment: value.append(str(line_segment)) value.append(str(blank_segment)) self.line_styles[index] = value # Grid # ------------------------------------------------------------------------- def set_grid(self, x_step, y_step, line_segment=1, \ blank_segment=0): self.grid = '%s,%s,%s,%s' % (x_step, y_step, line_segment, \ blank_segment) class ScatterChart(Chart): def type_to_url(self): return 'cht=s' def annotated_data(self): yield ('x', self.data[0]) yield ('y', self.data[1]) if len(self.data) > 2: # The optional third dataset is relative sizing for point # markers. yield ('marker-size', self.data[2]) class LineChart(Chart): def __init__(self, *args, **kwargs): if type(self) == LineChart: raise AbstractClassException('This is an abstract class') Chart.__init__(self, *args, **kwargs) class SimpleLineChart(LineChart): def type_to_url(self): return 'cht=lc' def annotated_data(self): # All datasets are y-axis data. for dataset in self.data: yield ('y', dataset) class SparkLineChart(SimpleLineChart): def type_to_url(self): return 'cht=ls' class XYLineChart(LineChart): def type_to_url(self): return 'cht=lxy' def annotated_data(self): # Datasets alternate between x-axis, y-axis. for i, dataset in enumerate(self.data): if i % 2 == 0: yield ('x', dataset) else: yield ('y', dataset) class BarChart(Chart): def __init__(self, *args, **kwargs): if type(self) == BarChart: raise AbstractClassException('This is an abstract class') Chart.__init__(self, *args, **kwargs) self.bar_width = None self.zero_lines = {} def set_bar_width(self, bar_width): self.bar_width = bar_width def set_zero_line(self, index, zero_line): self.zero_lines[index] = zero_line def get_url_bits(self, data_class=None, skip_chbh=False): url_bits = Chart.get_url_bits(self, data_class=data_class) if not skip_chbh and self.bar_width is not None: url_bits.append('chbh=%i' % self.bar_width) zero_line = [] if self.zero_lines: for index in xrange(max(self.zero_lines) + 1): if index in self.zero_lines: zero_line.append(str(self.zero_lines[index])) else: zero_line.append('0') url_bits.append('chp=%s' % ','.join(zero_line)) return url_bits class StackedHorizontalBarChart(BarChart): def type_to_url(self): return 'cht=bhs' class StackedVerticalBarChart(BarChart): def type_to_url(self): return 'cht=bvs' def annotated_data(self): for dataset in self.data: yield ('y', dataset) class GroupedBarChart(BarChart): def __init__(self, *args, **kwargs): if type(self) == GroupedBarChart: raise AbstractClassException('This is an abstract class') BarChart.__init__(self, *args, **kwargs) self.bar_spacing = None self.group_spacing = None def set_bar_spacing(self, spacing): """Set spacing between bars in a group.""" self.bar_spacing = spacing def set_group_spacing(self, spacing): """Set spacing between groups of bars.""" self.group_spacing = spacing def get_url_bits(self, data_class=None): # Skip 'BarChart.get_url_bits' and call Chart directly so the parent # doesn't add "chbh" before we do. url_bits = BarChart.get_url_bits(self, data_class=data_class, skip_chbh=True) if self.group_spacing is not None: if self.bar_spacing is None: raise InvalidParametersException('Bar spacing is required ' \ 'to be set when setting group spacing') if self.bar_width is None: raise InvalidParametersException('Bar width is required to ' \ 'be set when setting bar spacing') url_bits.append('chbh=%i,%i,%i' % (self.bar_width, self.bar_spacing, self.group_spacing)) elif self.bar_spacing is not None: if self.bar_width is None: raise InvalidParametersException('Bar width is required to ' \ 'be set when setting bar spacing') url_bits.append('chbh=%i,%i' % (self.bar_width, self.bar_spacing)) elif self.bar_width: url_bits.append('chbh=%i' % self.bar_width) return url_bits class GroupedHorizontalBarChart(GroupedBarChart): def type_to_url(self): return 'cht=bhg' class GroupedVerticalBarChart(GroupedBarChart): def type_to_url(self): return 'cht=bvg' def annotated_data(self): for dataset in self.data: yield ('y', dataset) class PieChart(Chart): def __init__(self, *args, **kwargs): if type(self) == PieChart: raise AbstractClassException('This is an abstract class') Chart.__init__(self, *args, **kwargs) self.pie_labels = [] if self.y_range: warnings.warn('y_range is not used with %s.' % \ (self.__class__.__name__)) def set_pie_labels(self, labels): self.pie_labels = [urllib.quote(a) for a in labels] def get_url_bits(self, data_class=None): url_bits = Chart.get_url_bits(self, data_class=data_class) if self.pie_labels: url_bits.append('chl=%s' % '%7c'.join(self.pie_labels)) return url_bits def annotated_data(self): # Datasets are all y-axis data. However, there should only be # one dataset for pie charts. for dataset in self.data: yield ('x', dataset) def scaled_data(self, data_class, x_range=None, y_range=None): if not x_range: x_range = [0, sum(self.data[0])] return Chart.scaled_data(self, data_class, x_range, self.y_range) class PieChart2D(PieChart): def type_to_url(self): return 'cht=p' class PieChart3D(PieChart): def type_to_url(self): return 'cht=p3' class VennChart(Chart): def type_to_url(self): return 'cht=v' def annotated_data(self): for dataset in self.data: yield ('y', dataset) class RadarChart(Chart): def type_to_url(self): return 'cht=r' class SplineRadarChart(RadarChart): def type_to_url(self): return 'cht=rs' class MapChart(Chart): def __init__(self, *args, **kwargs): Chart.__init__(self, *args, **kwargs) self.geo_area = 'world' self.codes = [] self.__areas = ('africa', 'asia', 'europe', 'middle_east', 'south_america', 'usa', 'world') self.__ccodes = ( 'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SV', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW') def type_to_url(self): return 'cht=t' def set_codes(self, codes): '''Set the country code map for the data. Codes given in a list. i.e. DE - Germany AT - Austria US - United States ''' codemap = '' for cc in codes: cc = cc.upper() if cc in self.__ccodes: codemap += cc else: raise UnknownCountryCodeException(cc) self.codes = codemap def set_geo_area(self, area): '''Sets the geo area for the map. * africa * asia * europe * middle_east * south_america * usa * world ''' if area in self.__areas: self.geo_area = area else: raise UnknownChartType('Unknown chart type for maps: %s' %area) def get_url_bits(self, data_class=None): url_bits = Chart.get_url_bits(self, data_class=data_class) url_bits.append('chtm=%s' % self.geo_area) if self.codes: url_bits.append('chld=%s' % ''.join(self.codes)) return url_bits def add_data_dict(self, datadict): '''Sets the data and country codes via a dictionary. i.e. {'DE': 50, 'GB': 30, 'AT': 70} ''' self.set_codes(datadict.keys()) self.add_data(datadict.values()) class GoogleOMeterChart(PieChart): """Inheriting from PieChart because of similar labeling""" def __init__(self, *args, **kwargs): PieChart.__init__(self, *args, **kwargs) if self.auto_scale and not self.x_range: warnings.warn('Please specify an x_range with GoogleOMeterChart, ' 'otherwise one arrow will always be at the max.') def type_to_url(self): return 'cht=gom' class QRChart(Chart): def __init__(self, *args, **kwargs): Chart.__init__(self, *args, **kwargs) self.encoding = None self.ec_level = None self.margin = None def type_to_url(self): return 'cht=qr' def data_to_url(self, data_class=None): if not self.data: raise NoDataGivenException() return 'chl=%s' % urllib.quote(self.data[0]) def get_url_bits(self, data_class=None): url_bits = Chart.get_url_bits(self, data_class=data_class) if self.encoding: url_bits.append('choe=%s' % self.encoding) if self.ec_level: url_bits.append('chld=%s%%7c%s' % (self.ec_level, self.margin)) return url_bits def set_encoding(self, encoding): self.encoding = encoding def set_ec(self, level, margin): self.ec_level = level self.margin = margin class ChartGrammar(object): def __init__(self): self.grammar = None self.chart = None def parse(self, grammar): self.grammar = grammar self.chart = self.create_chart_instance() for attr in self.grammar: if attr in ('w', 'h', 'type', 'auto_scale', 'x_range', 'y_range'): continue # These are already parsed in create_chart_instance attr_func = 'parse_' + attr if not hasattr(self, attr_func): warnings.warn('No parser for grammar attribute "%s"' % (attr)) continue getattr(self, attr_func)(grammar[attr]) return self.chart def parse_data(self, data): self.chart.data = data @staticmethod def get_possible_chart_types(): possible_charts = [] for cls_name in globals().keys(): if not cls_name.endswith('Chart'): continue cls = globals()[cls_name] # Check if it is an abstract class try: a = cls(1, 1, auto_scale=False) del a except AbstractClassException: continue # Strip off "Class" possible_charts.append(cls_name[:-5]) return possible_charts def create_chart_instance(self, grammar=None): if not grammar: grammar = self.grammar assert(isinstance(grammar, dict)) # grammar must be a dict assert('w' in grammar) # width is required assert('h' in grammar) # height is required assert('type' in grammar) # type is required chart_type = grammar['type'] w = grammar['w'] h = grammar['h'] auto_scale = grammar.get('auto_scale', None) x_range = grammar.get('x_range', None) y_range = grammar.get('y_range', None) types = ChartGrammar.get_possible_chart_types() if chart_type not in types: raise UnknownChartType('%s is an unknown chart type. Possible ' 'chart types are %s' % (chart_type, ','.join(types))) return globals()[chart_type + 'Chart'](w, h, auto_scale=auto_scale, x_range=x_range, y_range=y_range) def download(self): pass pygooglechart-0.3.0/setup.cfg000644 000766 000024 00000000073 11421530342 016103 0ustar00gakstaff000000 000000 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 pygooglechart-0.3.0/setup.py000644 000766 000024 00000001612 11421527536 016007 0ustar00gakstaff000000 000000 from distutils.core import setup from setuptools import setup from pygooglechart import __version__ setup(name='pygooglechart', version=__version__, py_modules=['pygooglechart'], description='A complete Python wrapper for the Google Chart API', author='Gerald Kaszuba', author_email='gerald@geraldkaszuba.com', url='http://pygooglechart.slowchop.com/', download_url='http://pygooglechart.slowchop.com/files/download/' \ 'pygooglechart-%s.tar.gz' % __version__, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: Visualization', 'Topic :: Software Development :: Libraries :: Python Modules', ], ) pygooglechart-0.3.0/test/000755 000766 000024 00000000000 11421530342 015241 5ustar00gakstaff000000 000000 pygooglechart-0.3.0/test/test_base.py000644 000766 000024 00000001625 11421527536 017603 0ustar00gakstaff000000 000000 #!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import sys import os import warnings import urllib ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, ROOT) import pygooglechart as gc class TestBase(unittest.TestCase): def setUp(self): # All tests require warnings to be raised self.raise_warnings(True) self.temp_image = 'temp.png' def tearDown(self): if os.path.exists(self.temp_image): os.unlink(self.temp_image) def raise_warnings(self, rw): gc._reset_warnings() if rw: warnings.simplefilter('error') else: # Don't print out warnings if we're expecting them--so we can have # nicer looking tests! :) warnings.simplefilter('ignore') def assertChartURL(self, url, query): self.assertTrue(url.endswith(query)) pygooglechart-0.3.0/test/test_bugs.py000644 000766 000024 00000000504 11421527536 017624 0ustar00gakstaff000000 000000 #!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import sys import os import warnings import urllib ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, ROOT) from test.test_base import TestBase import pygooglechart as gc if __name__ == "__main__": unittest.main() pygooglechart-0.3.0/test/test_general.py000644 000766 000024 00000013371 11421527536 020307 0ustar00gakstaff000000 000000 #!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import sys import os import warnings import urllib ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, ROOT) from test.test_base import TestBase import pygooglechart as gc class TestDataTypes(TestBase): def test_simple_data(self): s = gc.SimpleData([range(0, 62), [0, 1, 60, 61]]) self.assertEquals(repr(s), 'chd=s:ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz0123456789,AB89') def test_text_data(self): s = gc.TextData([[0, 1, 99.9]]) self.assertEquals(repr(s), 'chd=t:0.0,1.0,99.9') def test_ext_data(self): s = gc.ExtendedData([[0, 1, 4095]]) self.assertEquals(repr(s), 'chd=e:AAAB..') class TestScaling(TestBase): def test_simple_scale(self): sv = gc.SimpleData.scale_value self.raise_warnings(False) # We know some of these give warnings self.assertEquals(sv(-10, [0, 1]), 0) self.assertEquals(sv(0, [0, 1]), 0) self.assertEquals(sv(.5, [0, 1]), 31) self.assertEquals(sv(30, [0, 1]), 61) self.assertEquals(sv(2222, [0, 10000]), 14) # Test for warnings self.raise_warnings(True) self.assertRaises(UserWarning, sv, -10, [0, 1]) self.assertRaises(UserWarning, sv, 30, [0, 1]) def test_text_scale(self): sv = gc.TextData.scale_value self.raise_warnings(False) self.assertEquals(sv(-10, [0, 1]), 0) self.assertEquals(sv(0, [0, 1]), 0) self.assertEquals(sv(.5, [0, 1]), 50) self.assertEquals(sv(30, [0, 1]), 100) self.assertEquals(sv(2222, [0, 10000]), 22.22) self.raise_warnings(True) self.assertRaises(UserWarning, sv, -10, [0, 1]) self.assertRaises(UserWarning, sv, 30, [0, 1]) def test_ext_scale(self): sv = gc.ExtendedData.scale_value self.raise_warnings(False) self.assertEquals(sv(-10, [0, 1]), 0) self.assertEquals(sv(0, [0, 1]), 0) self.assertEquals(sv(.5, [0, 1]), 2048) self.assertEquals(sv(30, [0, 1]), 4095) self.assertEquals(sv(2222, [0, 10000]), 910) self.raise_warnings(True) self.assertRaises(UserWarning, sv, -10, [0, 1]) self.assertRaises(UserWarning, sv, 30, [0, 1]) class TestTitleStyle(TestBase): def test_title_style(self): chart = gc.SimpleLineChart(300, 100) chart.set_title_style() self.assertEquals(chart.title_colour, None) self.assertEquals(chart.title_font_size, None) chart = gc.SimpleLineChart(300, 100) chart.set_title_style(font_size=30) self.assertEquals(chart.title_colour, '333333') self.assertEquals(chart.title_font_size, 30) chart = gc.SimpleLineChart(300, 100) chart.set_title_style(colour='123456') self.assertEquals(chart.title_colour, '123456') self.assertEquals(chart.title_font_size, 13.5) chart = gc.SimpleLineChart(300, 100) chart.set_title_style(font_size=100, colour='123456') self.assertEquals(chart.title_colour, '123456') self.assertEquals(chart.title_font_size, 100) class TestLineChart(TestBase): def test_none_data(self): chart = gc.SimpleLineChart(300, 100) chart.add_data([1, 2, 3, None, 5]) print chart.get_url() self.assertChartURL(chart.get_url(), \ '?cht=lc&chs=300x100&chd=e:AAMzZm__zM') class TestQRChart(TestBase): def assertQRImage(self, chart, text): try: import PyQrcodec except ImportError: print 'PyQrCodec not installed. Can not test QR code image' return chart.download(self.temp_image) status, string = PyQrcodec.decode(self.temp_image) self.assertTrue(status) self.assertEquals(text, string) def test_simple(self): text = 'Hello World' chart = gc.QRChart(100, 150) chart.add_data(text) self.assertChartURL(chart.get_url(), \ '?cht=qr&chs=100x150&chl=Hello%20World') def test_encoding(self): chart = gc.QRChart(100, 100) chart.add_data('Hello World') self.assertChartURL(chart.get_url(), \ '?cht=qr&chs=100x100&chl=Hello%20World') def test_no_data(self): chart = gc.QRChart(100, 100) self.assertRaises(gc.NoDataGivenException, chart.get_url) def test_validate_image(self): text = 'Hello World' chart = gc.QRChart(100, 100) chart.add_data(text) chart.set_ec('H', 0) # PyQrcodec seems to only work on higher EC self.assertQRImage(chart, text) def test_validate_utf8(self): text = 'こんにちは世界' # Hello world in Japanese UTF-8 chart = gc.QRChart(100, 100) chart.add_data(text) chart.set_ec('H', 0) self.assertQRImage(chart, text) class TestGrammar(TestBase): types = ('Venn', 'GroupedHorizontalBar', 'GoogleOMeter', 'Scatter', 'StackedVerticalBar', 'Map', 'StackedHorizontalBar', 'SimpleLine', 'SparkLine', 'GroupedVerticalBar', 'SplineRadar', 'XYLine', 'Radar', 'QR') def test_chart_types(self): ret = gc.ChartGrammar.get_possible_chart_types() diff = set(ret).symmetric_difference(set(TestGrammar.types)) self.assert_(not diff) def test_google_chart(self): g = { 'type': 'GoogleOMeter', 'w': 100, 'h': 100, 'auto_scale': True, 'x_range': [ 0, 10 ], 'data': [ [ 1, 5, 10 ] ], } grammar = gc.ChartGrammar() chart = grammar.parse(g) # print chart.get_url() # chart.download('meh.png') if __name__ == "__main__": unittest.main() pygooglechart-0.3.0/pygooglechart.egg-info/dependency_links.txt000644 000766 000024 00000000001 11421530342 024671 0ustar00gakstaff000000 000000 pygooglechart-0.3.0/pygooglechart.egg-info/PKG-INFO000644 000766 000024 00000001362 11421530342 021722 0ustar00gakstaff000000 000000 Metadata-Version: 1.0 Name: pygooglechart Version: 0.3.0 Summary: A complete Python wrapper for the Google Chart API Home-page: http://pygooglechart.slowchop.com/ Author: Gerald Kaszuba Author-email: gerald@geraldkaszuba.com License: UNKNOWN Download-URL: http://pygooglechart.slowchop.com/files/download/pygooglechart-0.3.0.tar.gz Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Scientific/Engineering :: Visualization Classifier: Topic :: Software Development :: Libraries :: Python Modules pygooglechart-0.3.0/pygooglechart.egg-info/SOURCES.txt000644 000766 000024 00000000754 11421530342 022515 0ustar00gakstaff000000 000000 COPYING MANIFEST.in pygooglechart.py setup.py examples/all.py examples/bar.py examples/helper.py examples/labels.py examples/line.py examples/mapchart.py examples/pie.py examples/qrcodes.py examples/scatter.py examples/settings.py examples/venn.py examples/helpers/country_code_helper.py pygooglechart.egg-info/PKG-INFO pygooglechart.egg-info/SOURCES.txt pygooglechart.egg-info/dependency_links.txt pygooglechart.egg-info/top_level.txt test/test_base.py test/test_bugs.py test/test_general.pypygooglechart-0.3.0/pygooglechart.egg-info/top_level.txt000644 000766 000024 00000000016 11421530342 023352 0ustar00gakstaff000000 000000 pygooglechart pygooglechart-0.3.0/examples/all.py000644 000766 000024 00000001632 11421527536 017237 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ from glob import glob examples = glob('*.py') notexamples = ['settings.py', 'helper.py', 'all.py'] for example in examples: if example in notexamples: continue module = example[:-3] print module __import__(module).main() pygooglechart-0.3.0/examples/bar.py000644 000766 000024 00000004714 11421527536 017237 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys import math ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, '..')) from pygooglechart import StackedHorizontalBarChart, StackedVerticalBarChart, \ GroupedHorizontalBarChart, GroupedVerticalBarChart import settings def stacked_horizontal(): chart = StackedHorizontalBarChart(settings.width, settings.height, x_range=(0, 35)) chart.set_bar_width(10) chart.set_colours(['00ff00', 'ff0000']) chart.add_data([1,2,3,4,5]) chart.add_data([1,4,9,16,25]) chart.download('bar-horizontal-stacked.png') def stacked_vertical(): chart = StackedVerticalBarChart(settings.width, settings.height, y_range=(0, 35)) chart.set_bar_width(10) chart.set_colours(['00ff00', 'ff0000']) chart.add_data([1,2,3,4,5]) chart.add_data([1,4,9,16,25]) chart.download('bar-vertical-stacked.png') def grouped_horizontal(): chart = GroupedHorizontalBarChart(settings.width, settings.height, x_range=(0, 35)) chart.set_bar_width(5) chart.set_bar_spacing(2) chart.set_group_spacing(4) chart.set_colours(['00ff00', 'ff0000']) chart.add_data([1,2,3,4,5]) chart.add_data([1,4,9,16,25]) chart.download('bar-horizontal-grouped.png') def grouped_vertical(): chart = GroupedVerticalBarChart(settings.width, settings.height, y_range=(0, 35)) chart.set_bar_width(5) chart.set_colours(['00ff00', 'ff0000']) chart.add_data([1,2,3,4,5]) chart.add_data([1,4,9,16,25]) chart.download('bar-vertical-grouped.png') def main(): stacked_horizontal() stacked_vertical() grouped_horizontal() grouped_vertical() if __name__ == '__main__': main() pygooglechart-0.3.0/examples/helper.py000644 000766 000024 00000001704 11421527536 017746 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import random def random_data(points=50, maximum=100): return [random.random() * maximum for a in xrange(points)] def random_colour(min=20, max=200): func = lambda: int(random.random() * (max-min) + min) r, g, b = func(), func(), func() return '%02X%02X%02X' % (r, g, b) pygooglechart-0.3.0/examples/helpers/000755 000766 000024 00000000000 11421530342 017542 5ustar00gakstaff000000 000000 pygooglechart-0.3.0/examples/labels.py000644 000766 000024 00000004503 11421527536 017731 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys import math import random ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, '..')) from pygooglechart import SimpleLineChart from pygooglechart import Axis import settings import helper def cat_proximity(): """Cat proximity graph from http://xkcd.com/231/""" chart = SimpleLineChart(int(settings.width * 1.5), settings.height) chart.set_legend(['INTELLIGENCE', 'INSANITY OF STATEMENTS']) # intelligence data_index = chart.add_data([100. / y for y in xrange(1, 15)]) # insanity of statements chart.add_data([100. - 100 / y for y in xrange(1, 15)]) # line colours chart.set_colours(['208020', '202080']) # "Near" and "Far" labels, they are placed automatically at either ends. near_far_axis_index = chart.set_axis_labels(Axis.BOTTOM, ['FAR', 'NEAR']) # "Human Proximity to cat" label. Aligned to the center. index = chart.set_axis_labels(Axis.BOTTOM, ['HUMAN PROXIMITY TO CAT']) chart.set_axis_style(index, '202020', font_size=10, alignment=0) chart.set_axis_positions(index, [50]) chart.download('label-cat-proximity.png') def many_labels(): chart = SimpleLineChart(settings.width, settings.height) for a in xrange(3): for axis_type in (Axis.LEFT, Axis.RIGHT, Axis.BOTTOM): index = chart.set_axis_range(axis_type, 0, random.random() * 100) chart.set_axis_style(index, colour=helper.random_colour(), \ font_size=random.random() * 10 + 5) chart.add_data(helper.random_data()) chart.download('label-many.png') def main(): cat_proximity() many_labels() if __name__ == '__main__': main() pygooglechart-0.3.0/examples/line.py000644 000766 000024 00000011416 11421527536 017417 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys import math ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, '..')) from pygooglechart import Chart from pygooglechart import SimpleLineChart from pygooglechart import XYLineChart from pygooglechart import SparkLineChart from pygooglechart import Axis import settings import helper def simple_random(): chart = SimpleLineChart(settings.width, settings.height, y_range=(0, 100)) chart.add_data(helper.random_data()) chart.download('line-simple-random.png') def xy_random(): chart = XYLineChart(settings.width, settings.height, x_range=(0, 100), y_range=(0, 100)) chart.add_data(helper.random_data()) chart.add_data(helper.random_data()) chart.download('line-xy-random.png') def xy_rect(): chart = XYLineChart(settings.width, settings.height, x_range=(0, 100), y_range=(0, 100)) chart.add_data([10, 90, 90, 10, 10]) chart.add_data([10, 10, 90, 90, 10]) chart.download('line-xy-rect.png') def xy_circle(): chart = XYLineChart(settings.width, settings.height, x_range=(0, 100), y_range=(0, 100)) steps = 40 xradius = 25 yradius = 45 xmid = 50 ymid = 50 xlist = [] ylist = [] for angle in xrange(0, steps + 1): angle = float(angle) / steps * math.pi * 2 xlist.append(math.cos(angle) * xradius + xmid) ylist.append(math.sin(angle) * yradius + ymid) chart.add_data(xlist) chart.add_data(ylist) chart.download('line-xy-circle.png') def sparklines(): chart = SparkLineChart(settings.width, settings.height) chart.add_data(helper.random_data()) chart.download('line-sparkline.png') def fill(): # Set the vertical range from 0 to 50 max_y = 50 chart = SimpleLineChart(200, 125, y_range=[0, max_y]) # First value is the highest Y value. Two of them are needed to be # plottable. chart.add_data([max_y] * 2) # 3 sets of real data chart.add_data([28, 30, 31, 33, 35, 36, 42, 48, 43, 37, 32, 24, 28]) chart.add_data([16, 18, 18, 21, 23, 23, 29, 36, 31, 25, 20, 12, 17]) chart.add_data([7, 9, 9, 12, 14, 14, 20, 27, 21, 15, 10, 3, 7]) # Last value is the lowest in the Y axis. chart.add_data([0] * 2) # Black lines chart.set_colours(['000000'] * 5) # Filled colours # from the top to the first real data chart.add_fill_range('76A4FB', 0, 1) # Between the 3 data values chart.add_fill_range('224499', 1, 2) chart.add_fill_range('FF0000', 2, 3) # from the last real data to the chart.add_fill_range('80C65A', 3, 4) # Some axis data chart.set_axis_labels(Axis.LEFT, ['', max_y / 2, max_y]) chart.set_axis_labels(Axis.BOTTOM, ['Sep', 'Oct', 'Nov', 'Dec']) chart.download('line-fill.png') def stripes(): # Set the vertical range from 0 to 100 max_y = 100 # Chart size of 200x125 pixels and specifying the range for the Y axis chart = SimpleLineChart(200, 125, y_range=[0, max_y]) # Add the chart data data = [ 32, 34, 34, 32, 34, 34, 32, 32, 32, 34, 34, 32, 29, 29, 34, 34, 34, 37, 37, 39, 42, 47, 50, 54, 57, 60, 60, 60, 60, 60, 60, 60, 62, 62, 60, 55, 55, 52, 47, 44, 44, 40, 40, 37, 34, 34, 32, 32, 32, 31, 32 ] chart.add_data(data) # Set the line colour to blue chart.set_colours(['0000FF']) # Set the vertical stripes chart.fill_linear_stripes(Chart.CHART, 0, 'CCCCCC', 0.2, 'FFFFFF', 0.2) # Set the horizontal dotted lines chart.set_grid(0, 25, 5, 5) # The Y axis labels contains 0 to 100 skipping every 25, but remove the # first number because it's obvious and gets in the way of the first X # label. left_axis = range(0, max_y + 1, 25) left_axis[0] = '' chart.set_axis_labels(Axis.LEFT, left_axis) # X axis labels chart.set_axis_labels(Axis.BOTTOM, \ ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']) chart.download('line-stripes.png') def main(): simple_random() xy_random() xy_rect() xy_circle() sparklines() fill() stripes() if __name__ == '__main__': main() pygooglechart-0.3.0/examples/mapchart.py000644 000766 000024 00000003274 11421527536 020272 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, '..')) from pygooglechart import MapChart import settings import helper def birth_rate(): # Create a chart object of 200x100 pixels chart = MapChart(440, 220) # Load the data from a file, create a dict that looks like: # {'AU': 5, 'YE': 10} data = {} countries = open('mapchart-birth-rate.txt', 'rb').read().split('\n') for line in countries[:-1]: code, score = line.split(' ', 1) data[code] = float(score) # Set the data dictionary for country codes to value mapping chart.add_data_dict(data) # Download the chart chart.download('mapchart-birth-rate.png') # Now do it in africa ... chart.set_geo_area('africa') # ... with white as the default colour and gradient from green to red chart.set_colours(('EEEEEE', '10A010', 'D03000')) chart.download('mapchart-birth-rate-africa.png') def main(): birth_rate() if __name__ == '__main__': main() pygooglechart-0.3.0/examples/pie.py000644 000766 000024 00000003257 11421527536 017251 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, '..')) from pygooglechart import PieChart2D from pygooglechart import PieChart3D import settings import helper def hello_world(): # Create a chart object of 200x100 pixels chart = PieChart3D(250, 100) # Add some data chart.add_data([20, 10]) # Assign the labels to the pie data chart.set_pie_labels(['Hello', 'World']) # Download the chart chart.download('pie-hello-world.png') def house_explosions(): """ Data from http://indexed.blogspot.com/2007/12/meltdown-indeed.html """ chart = PieChart2D(int(settings.width * 1.7), settings.height) chart.add_data([10, 10, 30, 200]) chart.set_pie_labels([ 'Budding Chemists', 'Propane issues', 'Meth Labs', 'Attempts to escape morgage', ]) chart.download('pie-house-explosions.png') def main(): hello_world() house_explosions() if __name__ == '__main__': main() pygooglechart-0.3.0/examples/qrcodes.py000644 000766 000024 00000002257 11421527536 020133 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys import math ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, '..')) from pygooglechart import QRChart import settings import helper def hello(): # Create a 250x250 QR chart chart = QRChart(250, 250) # Add the text chart.add_data('Hello, World!') # "Level H" error correction with a 0 pixel margin chart.set_ec('H', 0) # Download chart.download('qr-hello.png') def main(): hello() if __name__ == '__main__': main() pygooglechart-0.3.0/examples/scatter.py000644 000766 000024 00000004267 11421527536 020143 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys import math ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, '..')) from pygooglechart import ScatterChart import settings import helper def scatter_random(): chart = ScatterChart(settings.width, settings.height, x_range=(0, 100), y_range=(0, 100)) chart.add_data(helper.random_data()) chart.add_data(helper.random_data()) chart.download('scatter-random.png') def scatter_random_marker_sizes(): chart = ScatterChart(settings.width, settings.height, x_range=(0, 100), y_range=(0, 100)) chart.add_data(helper.random_data()) chart.add_data(helper.random_data()) chart.add_data(helper.random_data()) chart.download('scatter-random-marker-sizes.png') def scatter_circle(): chart = ScatterChart(settings.width, settings.height, x_range=(0, 100), y_range=(0, 100)) steps = 40 xradius = 25 yradius = 45 xmid = 50 ymid = 50 xlist = [] ylist = [] for angle in xrange(0, steps + 1): angle = float(angle) / steps * math.pi * 2 xlist.append(math.cos(angle) * xradius + xmid) ylist.append(math.sin(angle) * yradius + ymid) chart.add_data(xlist) chart.add_data(ylist) chart.add_data(range(len(ylist))) chart.add_marker(0, 1.0, 'o', '00ff00', 10) chart.download('scatter-circle.png') def main(): scatter_random() scatter_random_marker_sizes() scatter_circle() if __name__ == '__main__': main() pygooglechart-0.3.0/examples/settings.py000644 000766 000024 00000000061 11421527536 020322 0ustar00gakstaff000000 000000 #!/usr/bin/env python width = 250 height = 100 pygooglechart-0.3.0/examples/venn.py000644 000766 000024 00000002440 11421527536 017433 0ustar00gakstaff000000 000000 #!/usr/bin/env python """ Copyright Gerald Kaszuba 2008 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . """ import os import sys ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(ROOT, '..')) from pygooglechart import VennChart import settings import helper def ultimate_power(): """ Data from http://indexed.blogspot.com/2007/08/real-ultimate-power.html """ chart = VennChart(settings.width, settings.height) chart.add_data([100, 100, 100, 20, 20, 20, 10]) chart.set_title('Ninjas or God') chart.set_legend(['unseen agents', 'super powerful', 'secret plans']) chart.download('venn-ultimate-power.png') def main(): ultimate_power() if __name__ == '__main__': main() pygooglechart-0.3.0/examples/helpers/country_code_helper.py000644 000766 000024 00000002556 11421527536 024173 0ustar00gakstaff000000 000000 class CountryCodes: ''' This is just a helper to generate useful data files. It isn't directly used in these examples. ''' def __init__(self): self.parse_codes_data() def parse_codes_data(self): lines = open('iso3166-1-a2.txt', 'rb').read().split('\n') self.codes = dict([ a.split(' ', 1) for a in lines[:-1] ]) def get_country_code_from_name(self, guess_name): best_score = 100 best_code = None for code, name in self.codes.items(): score = self.levenshtein(guess_name, name) if score < best_score: best_score = score best_code = code return best_code def levenshtein(self, a, b): "Calculates the Levenshtein distance between a and b." n, m = len(a), len(b) if n > m: # Make sure n <= m, to use O(min(n,m)) space a,b = b,a n,m = m,n current = range(n+1) for i in range(1,m+1): previous, current = current, [i]+[0]*n for j in range(1,n+1): add, delete = previous[j]+1, current[j-1]+1 change = previous[j-1] if a[j-1] != b[i-1]: change = change + 1 current[j] = min(add, delete, change) return current[n]